﻿<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
	<title xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory">Chapter 5. EPL Reference: Clauses</title>
	<link rel="stylesheet" href="css/espertech.css" type="text/css">
	<meta xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" name="generator" content="DocBook XSL-NS Stylesheets V1.74.0">
	<meta xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="home" href="index.html" title="Esper Reference">
	<link rel="up" href="index.html" title="Esper Reference">
	<link rel="prev" href="context.html" title="Chapter 4. Context and Context Partitions">
	<link rel="next" href="nwtable.html" title="Chapter 6. EPL Reference: Named Windows and Tables">
</head>

<body>
	<p xmlns:d="http://docbook.org/ns/docbook" id="title"><a href="./index.html" class="site_href"><strong>www.espertech.com</strong></a><a href="http://www.espertech.com/esper/esper-documentation/" class="doc_href"><strong>Documentation</strong></a></p>
	<ul xmlns:d="http://docbook.org/ns/docbook" class="docnav">
		<li class="previous"><a accesskey="p" href="context.html"><strong>Prev</strong></a></li>
		<li class="next"><a accesskey="n" href="nwtable.html"><strong>Next</strong></a></li>
	</ul>
	<div class="chapter" lang="en-US">
		<div class="titlepage">
			<div>
				<div>
					<h2 class="title"><a id="epl_clauses"></a>Chapter 5. EPL Reference: Clauses</h2>
				</div>
			</div>
		</div>
		<div class="toc">
			<dl>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-intro">5.1. EPL Introduction</a></span></dt>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-select-syntax">5.2. EPL Syntax</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-time-periods">5.2.1. Specifying Time Periods</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-comments">5.2.2. Using Comments</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-keywords">5.2.3. Reserved Keywords</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-escapestring">5.2.4. Escaping Strings</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-datatype">5.2.5. Data Types</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-javaconst">5.2.6. Using Constants and Enum Types</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-annotation">5.2.7. Annotation</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-expression-alias">5.2.8. Expression Alias</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-expression-decl">5.2.9. Expression Declaration</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-class-decl">5.2.10. Inlined-Class Declaration</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-script-decl">5.2.11. Script Declaration</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-context-decl">5.2.12. Referring to a Context</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-compositekey">5.2.13. Composite Keys and Array Values as Keys</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-select-list">5.3. Choosing Event Properties and Events: The Select Clause</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-select-all-props">5.3.1. Choosing the Event Itself: Select *</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-select-event-props">5.3.2. Choosing Specific Event Properties</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-select-expressions">5.3.3. Expressions</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-select-renaming">5.3.4. Renaming Event Properties</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-select-all-join">5.3.5. Choosing Event Properties and Events in a Join</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-select-pattern">5.3.6. Choosing Event Properties and Events From a Pattern</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-select-using-istream-rstream">5.3.7. Selecting Insert and Remove Stream Events</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-syntax-distinct">5.3.8. Select Distinct</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-transposefunc">5.3.9. Transposing an Expression Result to a Stream</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-selecteventbean">5.3.10. Selecting EventBean Instead of Underlying Event</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-from-clause">5.4. Specifying Event Streams: The From Clause</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-from-clause-filter">5.4.1. Filter-Based Event Streams</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-from-clause-patterns">5.4.2. Pattern-Based Event Streams</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-from-clause-window-spec">5.4.3. Specifying Data Windows</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-from-clause-view-multidatawindow">5.4.4. Multiple Data Windows</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-from-clause-stream-name">5.4.5. Using the Stream Name</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-from-clause-fromisoptional">5.4.6. The From-Clause is Optional</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-where-clause">5.5. Specifying Search Conditions: The Where Clause</a></span></dt>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-grouping-aggregating">5.6. Aggregates and Grouping: The Group-By Clause and the Having Clause</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-grouping-aggregate-functions">5.6.1. Using Aggregate Functions</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-grouping-group-by">5.6.2. Organizing Statement Results into Groups: The Group-by Clause</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-grouping-rollup">5.6.3. Using Group-By with Rollup, Cube and Grouping Sets</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-grouping-agglocal">5.6.4. Specifying Grouping for Each Aggregation Function</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-grouping-aggfilter">5.6.5. Specifying a Filter Expression for Each Aggregation Function</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-grouping-having">5.6.6. Selecting Groups of Events: The Having Clause</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-filter-where-grouping-having-interactions">5.6.7. How the Stream Filter, Where, Group By and Having-Clauses Interact</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-group-by-versus-view">5.6.8. Comparing Keyed Segmented Context, the Group By Clause and #groupwin for Data Windows</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-output-rate">5.7. Stabilizing and Controlling Output: The Output Clause</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-output-options">5.7.1. Output Clause Options</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-output-groupby">5.7.2. Aggregation, Group By, Having and Output Clause Interaction</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-order-by">5.8. Sorting Output: the Order By Clause</a></span></dt>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-limit">5.9. Limiting Row Count: the Limit Clause</a></span></dt>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-insert-into">5.10. Merging Streams and Continuous Insertion: The Insert Into Clause</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-property-transpose">5.10.1. Transposing a Property to a Stream</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-merging-columns">5.10.2. Merging Streams by Event Type</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-merging-types">5.10.3. Merging Disparate Types of Events: Variant Streams</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-decorated">5.10.4. Decorated Events</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-eventasproperty">5.10.5. Event as a Property</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-populate">5.10.6. Instantiating and Populating an Underlying Event Object</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-expression">5.10.7. Transposing an Expression Result</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-reconcile">5.10.8. Select-Clause Expression and Inserted-Into Column Event Type</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-typewithoutprops">5.10.9. Insert Into for Event Types Without Properties</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#insert-into-eventprecedence">5.10.10. Insert Into and Event Precedence</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-subqueries">5.11. Subqueries</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-subqueries-exists">5.11.1. The 'Exists' Keyword</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-subqueries-in">5.11.2. The 'In' and 'Not In' Keywords</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-subqueries-anysome">5.11.3. The 'Any' and 'Some' Keywords</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-subqueries-all">5.11.4. The 'All' Keyword</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-subqueries-groupby">5.11.5. Subquery With Group By Clause</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-subqueries-multicolumn">5.11.6. Multi-Column Selection</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-subqueries-multirow">5.11.7. Multi-Row Selection</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-subqueries-hints">5.11.8. Hints Related to Subqueries</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-join">5.12. Joining Event Streams</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-join-introducing">5.12.1. Introducing Joins</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-join-inner">5.12.2. Inner (Default) Joins</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-outerjoin">5.12.3. Outer, Left and Right Joins</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-unidirectional">5.12.4. Unidirectional Joins</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-unidirectional-fullouterjoin">5.12.5. Unidirectional Full Outer Joins</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-join-hints">5.12.6. Hints Related to Joins</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#histdata_overview">5.13. Accessing Relational Data via SQL</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_join">5.13.1. Joining SQL Query Results</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_join_where">5.13.2. SQL Query and the EPL Where Clause</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_outerjoin">5.13.3. Outer Joins With SQL Queries</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_polling_pattern">5.13.4. Using Patterns to Request (Poll) Data</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_polling">5.13.5. Polling SQL Queries via Iterator</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_implementation">5.13.6. JDBC Implementation Overview</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_nometadata">5.13.7. Oracle Drivers and No-Metadata Workaround</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_convert_cols">5.13.8. SQL Input Parameter and Column Output Conversion</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_convert_row">5.13.9. SQL Row POJO Conversion</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#histdata_fireandforget">5.13.10. Executing SQL Fire-and-Forget Queries Using EPFireAndForgetService</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#joining_method">5.14. Accessing Non-Relational Data via Method, Script or UDF Invocation</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#joining_method_syntax">5.14.1. Joining Method, Script or UDF Invocation Results</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#joining_method_polling">5.14.2. Polling Invocation Results via Iterator</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#joining_method_exposing">5.14.3. Providing the Method</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#joining_method_map">5.14.4. Using a Map Return Type</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#joining_method_oa">5.14.5. Using a Object Array Return Type</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#joining_method_eventbeanarray">5.14.6. Using an EventBean Return Type</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#joining_method_script">5.14.7. Providing the Script</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#joining_method_udf">5.14.8. Providing the UDF</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl_createschema">5.15. Declaring an Event Type: Create Schema</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl_createschema_properties">5.15.1. Declare an Event Type by Providing Names and Types</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl_createschema_class">5.15.2. Declare an Event Type by Providing a Class Name</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl_createschema_variant">5.15.3. Declare a Variant Stream</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#split_overview">5.16. Splitting and Duplicating Streams</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#split_containedeventselect">5.16.1. Generating Marker Events for Contained Events</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#split_atdrop">5.16.2. Splitting Streams with @Priority and @Drop</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#variables_overview">5.17. Variables and Constants</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#variable_create">5.17.1. Creating Variables: The Create Variable Clause</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#variable_set">5.17.2. Setting Variable Values: The On Set Clause</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#variable_using">5.17.3. Using Variables</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#variable_object">5.17.4. Object-Type Variables</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#variable_eventtype">5.17.5. Class and Event-Type Variables</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#create-exprglobal">5.18. Declaring Global Expressions, Aliases and Scripts: Create Expression</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#create-exprglobal-alias">5.18.1. Global Expression Aliases</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#create-exprglobal-expr">5.18.2. Global Expression Declarations</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#create-exprglobal-script">5.18.3. Global Scripts</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-containedeventselect">5.19. Contained-Event Selection</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-select">5.19.1. Select-Clause in a Contained-Event Selection</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-where">5.19.2. Where Clause in a Contained-Event Selection</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-join">5.19.3. Contained-Event Selection and Joins</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-pojoexample">5.19.4. Sentence and Word Example</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-examples">5.19.5. More Examples</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-arrayofprimitive">5.19.6. Contained Expression Returning an Array of Property Values</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-arrayofevent">5.19.7. Contained Expression Returning an Array of EventBean</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-collectionofundeventobj">5.19.8. Contained Expression Returning a Collection of Underlying Event Objects</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-beginend">5.19.9. Generating Marker Events Such as a Begin and End Event</a></span></dt>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-containedeventselect-restrictions">5.19.10. Contained-Event Limitations</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-update">5.20. Updating an Insert Stream: The Update IStream Clause</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="epl_clauses.html#epl-update-object">5.20.1. Immutability and Updates</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="epl_clauses.html#epl-grouped-delivery">5.21. Controlling Event Delivery : The For Clause</a></span></dt>
			</dl>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-intro"></a>5.1. EPL Introduction</h2>
					</div>
				</div>
			</div>
			<p>
				The Event Processing Language (EPL) is a SQL-standard language with extensions, offering <code class="literal">SELECT</code>, <code class="literal">FROM</code>, <code class="literal">WHERE</code>, <code class="literal">GROUP BY</code>, <code class="literal">HAVING</code> and <code class="literal">ORDER BY</code> clauses. Streams replace tables as the source of data with events replacing rows as the basic unit of data. Since events are composed of data, the SQL concepts of correlation through joins, subqueries and aggregation through grouping can be effectively leveraged.
			</p>
			<p>
				The <code class="literal">INSERT INTO</code> clause is recast as a means of forwarding events to other streams for further processing. External data may be queried and joined with the stream data. Additional clauses such as the <code class="literal">PATTERN</code> and <code class="literal">OUTPUT</code> clauses are available to provide the missing SQL language constructs specific to event processing.
			</p>
			<p>
				Statements can specify data windows. Similar to tables in a SQL statement, data windows define the subset of events to be analyzed.
				Data windows can be combined to an intersection or union of sets of events.
				Some of the often-used data windows are <code class="literal">#length</code>, <code class="literal">#time</code>, <code class="literal">#unique</code>, <code class="literal">#lastevent</code>, <code class="literal">#firstevent</code> and <code class="literal">#keepall</code>.
			</p>
			<p>
				EPL provides the concept of <span class="emphasis"><em>named window</em></span>. Named windows are data windows that can be used by multiple statements.
				The name of a named window can occur in a statement's <code class="literal">FROM</code> clause to query the named window or to include the named window in a join or subquery.
			</p>
			<p>
				EPL provides the concept of <span class="emphasis"><em>table</em></span>. Tables are globally-visible data structures that typically have primary key columns and that can hold aggregation state.
				An overview of named windows and tables, and a comparison between them, can be found at <a class="xref" href="nwtable.html#nwtable-overview" title="6.1. Overview">Section 6.1, “Overview”</a>.
			</p>
			<p>
				EPL allows execution of fire-and-forget (on-demand, non-continuous, triggered by API) queries against named windows and tables through the runtime API. The statement compiler automatically indexes named window data for fast access by <code class="literal">ON SELECT/MERGE/UPDATE/INSERT/DELETE</code> without the need to create an index explicitly, or can access explicit (secondary) table indexes for operations on tables. For fast fire-and-forget query execution via runtime API use the <code class="literal">CREATE INDEX</code> syntax to create an explicit index for the named window or table in question.
			</p>
			<p>
				Use <code class="literal">CREATE SCHEMA</code> to declare an event type.
			</p>
			<p>
				<span class="emphasis"><em>Variables</em></span> can come in handy to parameterize statements and change parameters on-the-fly and in response to events. Variables can be used in an expression anywhere in a statement as well as in the output clause for dynamic control of output rates.
			</p>
			<p>
				The compiler and runtime can be extended by plugging-in custom developed data windows, aggregation functions, and more.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-select-syntax"></a>5.2. EPL Syntax</h2>
					</div>
				</div>
			</div>
			<p>
				Statement are compiled and deployed into the runtime, and publish results to listeners as events are received by the runtime or time advances that match the criteria specified in the statement. Events can also be obtained from polling statement via the <code class="literal">safeIterator</code> and <code class="literal">iterator</code> methods that provide a pull-data API.
			</p>
			<p>
				The <code class="literal">select</code> clause in a statement specifies the event properties or events to retrieve. The <code class="literal">from</code> clause in a statement specifies the event stream definitions and stream names to use. The <code class="literal">where</code> clause in n statement specifies search conditions that specify which event or event combination to search for. For example, the following statement returns the average price for IBM stock ticks in the last 30 seconds.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select avg(price) from StockTick#time(30 sec) where symbol='IBM'</pre>
			<p>
				Statements follow the below syntax. Statements can be simple queries or more complex queries. A simple select contains only a <code class="literal">select</code> clause and a single stream definition. Complex statements can be build that feature a more elaborate select list utilizing expressions, may join multiple streams, may contain a <code class="literal">where</code> clause with search conditions and so on.
			</p>
			<pre class="synopsis">[<span class="emphasis"><em>annotations</em></span>]
[<span class="emphasis"><em>expression_declarations</em></span>]
[context <span class="emphasis"><em>context_name</em></span>]
[into table <span class="emphasis"><em>table_name</em></span>]
[insert into <span class="emphasis"><em>insert_into_def</em></span>]
select <span class="emphasis"><em>select_list</em></span>
from <span class="emphasis"><em>stream_def</em></span> [as name] [, <span class="emphasis"><em>stream_def</em></span> [as name]] [,...]
[where <span class="emphasis"><em>search_conditions</em></span>]
[group by <span class="emphasis"><em>grouping_expression_list</em></span>]
[having <span class="emphasis"><em>grouping_search_conditions</em></span>]
[output <span class="emphasis"><em>output_specification</em></span>]
[order by <span class="emphasis"><em>order_by_expression_list</em></span>]
[limit <span class="emphasis"><em>num_rows</em></span>]
</pre>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-time-periods"></a>5.2.1. Specifying Time Periods</h3>
						</div>
					</div>
				</div>
				<p>
					Time-based windows as well as pattern observers and guards take a time period as a parameter. Time periods follow the syntax below.
				</p>
				<pre class="synopsis">time-period : [<span class="emphasis"><em>year-part</em></span>] [<span class="emphasis"><em>month-part</em></span>] [<span class="emphasis"><em>week-part</em></span>] [<span class="emphasis"><em>day-part</em></span>] [<span class="emphasis"><em>hour-part</em></span>] 
      [<span class="emphasis"><em>minute-part</em></span>] [<span class="emphasis"><em>seconds-part</em></span>] [<span class="emphasis"><em>milliseconds-part</em></span>] [<span class="emphasis"><em>microseconds-part</em></span>]

year-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("years" | "year")
month-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("months" | "month")
week-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("weeks" | "week")
day-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("days" | "day")
hour-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("hours" | "hour")
minute-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("minutes" | "minute" | "min")
seconds-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("seconds" | "second" | "sec")
milliseconds-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("milliseconds" | "millisecond" | "msec")
microseconds-part : <span class="emphasis"><em>(number|variable_name)</em></span> ("microseconds" | "microsecond" | "usec")</pre>
				<p>
					Some examples of time periods are:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">10 seconds
10 minutes 30 seconds
20 sec 100 msec
1 day 2 hours 20 minutes 15 seconds 110 milliseconds 5 microseconds
0.5 minutes
1 year
1 year 1 month</pre>
				<p>
					Variable names and substitution parameters '<code class="literal">?</code>' for prepared statements are also allowed as part of a time period expression.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						When the time period has a month or year part, all values must be integer-type values.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-comments"></a>5.2.2. Using Comments</h3>
						</div>
					</div>
				</div>
				<p>
					Comments can appear anywhere in the module and statement text where whitespace is allowed. Comments can be written in two ways: slash-slash (<code class="literal">// ...</code>) comments and slash-star (<code class="literal">/* ... */</code>) comments.
				</p>
				<p>
					Slash-slash comments extend to the end of the line:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// This comment extends to the end of the line.
// Two forward slashes with no whitespace between them begin such comments.

select * from MyEvent  // this is a slash-slash comment

// All of this text together is a valid statement.</pre>
				<p>
					Slash-star comments can span multiple lines:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">/* This comment is a "slash-star" comment that spans multiple lines.
 * It begins with the slash-star sequence with no space between the '/' and '*' characters.
 * By convention, subsequent lines can begin with a star and are aligned, but this is 
 * not required.
 */		
select * from MyEvent  /* this also works */</pre>
				<p>
					Comments styles can also be mixed:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select field1, // first comment
  /* second comment*/  field2
  from MyEvent</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-keywords"></a>5.2.3. Reserved Keywords</h3>
						</div>
					</div>
				</div><a id="d0e6373" class="indexterm"></a>
				<p>
					Certain words such as <code class="literal">select</code>, <code class="literal">delete</code> or <code class="literal">set</code> are reserved and may not be used as identifiers. Please consult <a class="xref" href="appendix_keywords.html" title="Appendix C. Reserved Keywords">Appendix C, <i>Reserved Keywords</i></a> for the list of reserved keywords and permitted keywords.
				</p>
				<p>
					Names of built-in functions and certain auxiliary keywords are permitted as event property names and in the rename syntax of the <code class="literal">select</code> clause. For example, <code class="literal">count</code> is acceptable.
				</p>
				<p>
					Consider the example below, which assumes that <code class="literal">'last'</code> is an event property of MyEvent:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// valid
select last, count(*) as count from MyEvent</pre>
				<p>
					This example shows an incorrect use of a reserved keyword:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// invalid
select insert from MyEvent</pre>
				<p>
					EPL offers an escape syntax for reserved keywords: Event properties as well as event or stream names may be escaped via the backwards apostrophe <code class="literal">`</code> (ASCII 96) character.
				</p>
				<p>
					The next example queries an event type by name <code class="literal">Order</code> (a reserved keyword) that provides a property by name <code class="literal">insert</code> (a reserved keyword):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// valid
select `insert` from `Order`</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-escapestring"></a>5.2.4. Escaping Strings</h3>
						</div>
					</div>
				</div><a id="d0e6426" class="indexterm"></a>
				<p>
					You may surround string values by either double-quotes (<code class="literal">"</code>) or single-quotes (<code class="literal">'</code>). When your string constant in a statement itself contains double quotes or single quotes,
					you must escape the quotes.
				</p>
				<p>
					Double and single quotes may be escaped by the backslash (<code class="literal">\</code>) character or by unicode notation. Unicode 0027 is a single quote (<code class="literal">'</code>) and 0022 is a double quote (<code class="literal">"</code>).
				</p>
				<p>
					Escaping event property names is described in <a class="xref" href="event_representation.html#eventrep-properties-escaping" title="3.2.1. Escape Characters">Section 3.2.1, “Escape Characters”</a>.
				</p>
				<p>
					The sample EPL below escapes the single quote in the string constant <code class="literal">John's</code>, and filters out order events where the name value matches:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from OrderEvent(name='John\'s')
// ...equivalent to...
select * from OrderEvent(name='John\u0027s')</pre>
				<p>
					The next EPL escapes the string constant <code class="literal">Quote "Hello"</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from OrderEvent(description like "Quote \"Hello\"")
// is equivalent to
select * from OrderEvent(description like "Quote \u0022Hello\u0022")</pre>
				<p>
					When building an escape string via the API, escape the backslash, as shown in below code snippet:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">compiler.compile("select * from OrderEvent(name='John\\'s')", ...);
// ... and for double quotes...
compiler.compile("select * from OrderEvent(description like \"Quote \\\"Hello\\\"\")", ...);</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-datatype"></a>5.2.5. Data Types</h3>
						</div>
					</div>
				</div><a id="d0e6473" class="indexterm"></a>
				<p>
					For NEsper .NET also see <a class="xref" href="appendix_dotnet.html#appendix_dotnet_epl_syntax_datatype" title="J.13. .NET EPL Syntax - Data Types">Section J.13, “.NET EPL Syntax - Data Types”</a>.
				</p>
				<p>
					EPL honors all Java built-in primitive and boxed types, including <code class="literal">java.math.BigInteger</code> and <code class="literal">java.math.BigDecimal</code>.
				</p>
				<p>
					EPL also follows Java standards in terms of widening, performing widening automatically in cases where widening type conversion is allowed without loss of precision, for both boxed and primitive types and including <code class="literal">BigInteger</code> and <code class="literal">BigDecimal</code>:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								byte to short, int, long, float, double, BigInteger or BigDecimal
							</p>
						</li>
						<li>
							<p>
								short to int, long, float, or double, BigInteger or BigDecimal
							</p>
						</li>
						<li>
							<p>
								char to int, long, float, or double, BigInteger or BigDecimal
							</p>
						</li>
						<li>
							<p>
								int to long, float, or double, BigInteger or BigDecimal
							</p>
						</li>
						<li>
							<p>
								long to float or double, BigInteger or BigDecimal
							</p>
						</li>
						<li>
							<p>
								float to double or BigDecimal
							</p>
						</li>
						<li>
							<p>
								double to BigDecimal
							</p>
						</li>
					</ol>
				</div>
				<p>
					In cases where loss of precision is possible because of narrowing requirements, EPL compilation outputs a compilation error.
				</p>
				<p>
					EPL supports casting via the <code class="literal">cast</code> function.
				</p>
				<p>
					EPL returns double-type values for division regardless of operand type. EPL can also be configured to follow Java rules for integer arithmetic instead as described in <a class="xref" href="configuration.html#configuration-compiler-expression" title="17.5.6. Compiler Settings Related to Expression Evaluation">Section 17.5.6, “Compiler Settings Related to Expression Evaluation”</a>.
				</p>
				<p>
					Division by zero returns positive or negative infinity. Division by zero can be configured to return null instead.
				</p>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-datatype-constants"></a>5.2.5.1. Data Type of Constants</h4>
							</div>
						</div>
					</div><a id="d0e6534" class="indexterm"></a><a id="d0e6537" class="indexterm"></a>
					<p>
						An EPL constant is a number or a character string that indicates a fixed value. Constants can be used as expressions in many statements, including variable assignment and case-when statements. They can also be used as parameter values for many built-in objects and clauses. Constants are also called literals.
					</p>
					<p>
						EPL supports the standard SQL constant notation as well as Java data type literals.
					</p>
					<p>
						The following are types of EPL constants:
					</p>
					<div class="table"><a id="d0e6546"></a>
						<p class="title"><b>Table 5.1. Types of EPL constants</b></p>
						<div class="table-contents">
							<table summary="Types of EPL constants" border="1">
								<colgroup>
									<col>
									<col>
									<col>
								</colgroup>
								<thead>
									<tr>
										<th>Type</th>
										<th>Description</th>
										<th>Examples</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td>string</td>
										<td>A single character to an unlimited number of characters. Valid delimiters are the single quote (') or double quote (").</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 'volume' as field1,
   "sleep" as field2, 
  "\u0041" as unicodeA</pre>
										</td>
									</tr>
									<tr>
										<td>boolean</td>
										<td>A boolean value.</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select true as field1, 
  false as field2</pre>
										</td>
									</tr>
									<tr>
										<td>integer</td>
										<td>An integer value (4 byte).</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 1 as field1, 
  -1 as field2, 
  1e2 as field3</pre>
										</td>
									</tr>
									<tr>
										<td>long</td>
										<td>A long value (8 byte). Use the "L" or "l" (lowercase L) suffix.</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 1L as field1, 
  1l as field2</pre>
										</td>
									</tr>
									<tr>
										<td>double</td>
										<td>A double-precision 64-bit IEEE 754 floating point.</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 1.67 as field1, 
  167e-2 as field2, 
  1.67d as field3</pre>
										</td>
									</tr>
									<tr>
										<td>float</td>
										<td>A single-precision 32-bit IEEE 754 floating point. Use the "f" suffix.</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 1.2f as field1, 
  1.2F as field2</pre>
										</td>
									</tr>
									<tr>
										<td>byte</td>
										<td>A 8-bit signed two's complement integer.</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 0x10 as field1</pre>
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div><br class="table-break">
					<p>
						EPL does not have a single-byte character data type for its literals. Single character literals are treated as string.
					</p>
					<p>
						Internal byte representation and boundary values of constants follow the Java standard.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-datatype-bignumber"></a>5.2.5.2. BigInteger and BigDecimal</h4>
							</div>
						</div>
					</div>
					<p>
						EPL automatically performs widening of numbers to <code class="literal">BigInteger</code> and <code class="literal">BigDecimal</code> as required, and employs the respective <code class="literal">equals</code>, <code class="literal">compareTo</code> and arithmetic methods provided by <code class="literal">BigInteger</code> and <code class="literal">BigDecimal</code>.
					</p>
					<p>
						To explicitly create <code class="literal">BigInteger</code> and <code class="literal">BigDecimal</code> constants in EPL, please use the cast syntax : <code class="literal">cast(</code><span class="emphasis"><em>value</em></span><code class="literal">, BigInteger)</code>.
					</p>
					<p>
						Note that since <code class="literal">BigDecimal.valueOf(1.0)</code> is not the same as <code class="literal">BigDecimal.valueOf(1)</code> (in terms of equality through <code class="literal">equals</code>), care should be taken towards the consistent use of scale.
					</p>
					<p>
						When using aggregation functions for <code class="literal">BigInteger</code> and <code class="literal">BigDecimal</code> values, please note these limitations:
					</p>
					<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
						<ol>
							<li>
								<p>
									The <code class="literal">median</code>, <code class="literal">stddev</code> and <code class="literal">avedev</code> aggregation functions operate on the double value of the object and return a double value.
								</p>
							</li>
							<li>
								<p>
									All other aggregation functions return <code class="literal">BigDecimal</code> or <code class="literal">BigInteger</code> values (except <code class="literal">count</code>).
								</p>
							</li>
						</ol>
					</div>
					<p>
						For <code class="literal">BigDecimal</code> precision and rounding, please see <a class="xref" href="configuration.html#configuration-compiler-expression-mathcontext" title="17.5.6.5. Math Context">Section 17.5.6.5, “Math Context”</a>. For division operations with BigDecimal number we recommend
						configuring a math context.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-javaconst"></a>5.2.6. Using Constants and Enum Types</h3>
						</div>
					</div>
				</div><a id="d0e6714" class="indexterm"></a><a id="d0e6717" class="indexterm"></a>
				<p>
					This chapter is about Java language constants and enum types and their use in EPL expressions.
				</p>
				<p>
					Java language constants are public static final fields in Java that may participate in expressions of all kinds, as this example shows:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MyEvent where property = MyConstantClass.FIELD_VALUE</pre>
				<p>
					Event properties that are enumeration values can be compared by their enum type value:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MyEvent where enumProp = EnumClass.ENUM_VALUE_1</pre>
				<p>
					Event properties can also be passed to enum type functions or compared to an enum type method result:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MyEvent where somevalue = EnumClass.ENUM_VALUE_1.getSomeValue()
  or EnumClass.ENUM_VALUE_2.analyze(someothervalue)</pre>
				<p>
					Enum types have a <code class="literal">valueOf</code> method that returns the enum type value:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MyEvent where enumProp = EnumClass.valueOf('ENUM_VALUE_1')</pre>
				<p>
					If your application does not import, through configuration, the package that contains the enumeration class, then it must also specify the package name of the class. Enum types that are inner classes must be qualified with <code class="literal">$</code> following Java conventions.
				</p>
				<p>
					For example, the Color enum type as an inner class to <code class="literal">MyEvent</code> in package <code class="literal">org.myorg</code> can be referenced as shown:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MyEvent(enumProp=org.myorg.MyEvent$Color.GREEN)#firstevent</pre>
				<p>
					Instance methods may also be invoked on event instances by specifying a stream name, as shown below:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select myevent.computeSomething() as result from MyEvent as myevent</pre>
				<p>
					Chaining instance methods is supported as this example shows:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select myevent.getComputerFor('books', 'movies').calculate() as result 
from MyEvent as myevent</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-annotation"></a>5.2.7. Annotation</h3>
						</div>
					</div>
				</div><a id="d0e6767" class="indexterm"></a>
				<p>
					An annotation is an addition made to information in a statement. EPL provides certain built-in annotations for defining statement name, adding a statement description or for tagging statements such as for managing statements or directing statement output.
					Other than the built-in annotations, applications can provide their own annotation classes that the EPL compiler can populate.
				</p>
				<p>
					An annotation is part of the statement text and precedes the statement. Annotations are therefore part of the EPL grammar. The syntax for annotations follows the host language (Java, .NET) annotation syntax:
				</p>
				<pre class="synopsis">@<span class="emphasis"><em>annotation_name</em></span> [(<span class="emphasis"><em>annotation_parameters</em></span>)]</pre>
				<p>
					An annotation consists of the annotation name and optional annotation parameters. The <span class="emphasis"><em>annotation_name</em></span> is the simple class name or fully-qualified class name of the annotation class. The optional <span class="emphasis"><em>annotation_parameters</em></span>
					are a list of key-value pairs following the syntax:
				</p>
				<pre class="synopsis">@<span class="emphasis"><em>annotation_name</em></span> (<span class="emphasis"><em>attribute_name</em></span> = <span class="emphasis"><em>attribute_value</em></span>, [name=value, ...])</pre>
				<p>
					The <span class="emphasis"><em>attribute_name</em></span> is an identifier that must match the attributes defined by the annotation class. An <span class="emphasis"><em>attribute_value</em></span> is a constant of any of the primitive types or string, an array, an enum type value or another (nested) annotation. Null values are not allowed as annotation attribute values. Enumeration values are supported in statements and not support in statements created via the <code class="literal">createPattern</code> method.
				</p>
				<p>
					Use the <code class="literal">getAnnotations</code> method of <code class="literal">EPStatement</code> to obtain annotations.
				</p>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-application"></a>5.2.7.1. Application-Provided Annotations</h4>
							</div>
						</div>
					</div><a id="d0e6823" class="indexterm"></a>
					<p>
						Your application may provide its own annotation classes. The compiler detects and populates annotation instances for application annotation classes.
					</p>
					<p>
						The name of application-provided annotations is case-sensitive.
					</p>
					<p>
						To enable the compiler to recognize application annotation classes, your annotation name must include the package name (i.e. be fully-qualified) or your compiler configuration must import the annotation class or package via the configuration API.
					</p>
					<p>
						For example, assume that your application defines an annotation in its application code as follows:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public @interface ProcessMonitor {
  String processName();
  boolean isLongRunning default false;
  int[] subProcessIds;
}</pre>
					<p>
						Shown next is a statement that utilizes the annotation class defined earlier:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@ProcessMonitor(processName='CreditApproval',
  isLongRunning=true, subProcessIds = {1, 2, 3} )
  
select count(*) from ProcessEvent(processId in (1, 2, 3)#time(30)</pre>
					<p>
						Above example assumes the <code class="literal">ProcessMonitor</code> annotation class is imported via configuration XML or API.
					</p>
					<p>
						If <code class="literal">ProcessMonitor</code> should only be visible for use in annotations, use <code class="literal">addAnnotationImport</code> (or the <code class="literal">auto-import-annotations</code> XML tag).
						If <code class="literal">ProcessMonitor</code> should be visible in all of EPL including annotations, use <code class="literal">addImport</code> (or the <code class="literal">auto-import</code> XML tag).
					</p>
					<p>
						Here is an example API call to import for annotation-only all classes in package <code class="literal">com.mycompany.app.myannotations</code>:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">Configuration configuration = new Configuration();
configuration.getCommon().addAnnotationImport("com.mycompany.app.myannotations.*");</pre>
					<p>
						The next example imports the <code class="literal">ProcessMonitor</code> class only and only for annotation use:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">Configuration configuration = new Configuration();
configuration.getCommon().addAnnotationImport("com.mycompany.myannotations.ProcessMonitor");</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-withenum"></a>5.2.7.2. Annotations With Enumeration Values</h4>
							</div>
						</div>
					</div><a id="d0e6884" class="indexterm"></a>
					<p>
						For annotations that accept an enumeration value, the enumeration name does not need to be specified and matching is not case-sensitive.
					</p>
					<p>
						For example, assume the enum is:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public enum MyEnum {
    ENUM_VALUE_1,
    ENUM_VALUE_2;
}</pre>
					<p>
						Assume the annotation is:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public @interface MyAnnotationWithEnum {
    MyEnum myEnum();
}</pre>
					<p>
						The statement can specify:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@MyAnnotationWithEnum(myEnum = enum_value_1) select * from MyEvent</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-builtin"></a>5.2.7.3. Built-In Statement Annotations</h4>
							</div>
						</div>
					</div><a id="d0e6906" class="indexterm"></a>
					<p>
						The name of built-in annotations is not case-sensitive, allowing both <code class="literal">@NAME</code> or <code class="literal">@name</code>, for example.
					</p>
					<p>
						The list of built-in statement-level annotations is:
					</p>
					<div class="table"><a id="d0e6921"></a>
						<p class="title"><b>Table 5.2. Built-In Statement Annotations</b></p>
						<div class="table-contents">
							<table summary="Built-In Statement Annotations" border="1">
								<colgroup>
									<col>
									<col>
									<col>
								</colgroup>
								<thead>
									<tr>
										<th>Name</th>
										<th>Purpose and Attributes</th>
										<th>Example</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td>Name</td>
										<td>
											<p>Provides a statement name. Attributes are:</p>
											<p>value : Statement name.</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Name("MyStatementName")</pre>
										</td>
									</tr>
									<tr>
										<td>Description</td>
										<td>
											<p>Provides a statement description. Attributes are:</p>
											<p>value : Statement description.</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Description("Place statement
description here.")</pre>
										</td>
									</tr>
									<tr>
										<td>Tag</td>
										<td>
											<p>For tagging a statement with additional information. Attributes are:</p>
											<p>name : Tag name.</p>
											<p>value : Tag value.</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Tag(name="MyTagName", 
 value="MyTagValue")</pre>
										</td>
									</tr>
									<tr>
										<td>Priority</td>
										<td>
											<p>Applicable when an event (or schedule) matches filter criteria for multiple statements: Defines the order of statement processing (requires an runtime-level setting).</p>
											<p>Attributes are:</p>
											<p>value : priority value.</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Priority(10)</pre>
										</td>
									</tr>
									<tr>
										<td>Drop</td>
										<td>
											<p>Applicable when an event (or schedule) matches filter criteria for multiple statements, drops the event after processing the statement (requires a runtime-level setting).</p>
											<p>No attributes.</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Drop</pre>
										</td>
									</tr>
									<tr>
										<td>Hint</td>
										<td>
											<p>For providing one or more hints towards how the runtime should execute a statement. Attributes are:</p>
											<p>value : A comma-separated list of one or more case-insensitive keywords.</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hint('iterate_only')</pre>
										</td>
									</tr>
									<tr>
										<td>Hook</td>
										<td>
											<p>Use this annotation to register one or more statement-specific hooks providing a hook type for each individual hook, such as for SQL parameter, column or row conversion.</p>
											<p>Attributes are the hook <code class="literal">type</code> and the <code class="literal">hook</code> itself (usually a import or class name):</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hook(type=HookType.SQLCOL,
  hook='MyDBTypeConvertor')</pre>
										</td>
									</tr>
									<tr>
										<td>Audit</td>
										<td>
											<p>Causes the runtime to output detailed processing information for a statement.</p>
											<p>optional value : A comma-separated list of one or more case-insensitive keywords.</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Audit</pre>
										</td>
									</tr>
									<tr>
										<td>EventRepresentation</td>
										<td>
											<p>Causes the compiler to use a specific event representation for output and internal event types.</p>
										</td>
										<td>
											<p>
												For Object-Array:
											</p>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@EventRepresentation(objectarray)</pre>
											<p>
												For JSON:
											</p>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@EventRepresentation(json)</pre>
											<p>
												For Map:
											</p>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@EventRepresentation(map)</pre>
											<p>
												For Avro:
											</p>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@EventRepresentation(avro)</pre>
										</td>
									</tr>
									<tr>
										<td>IterableUnbound</td>
										<td>
											<p>For use when iterating statements with unbound streams, instructs the compiler to retain the last event for iterating.</p>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@IterableUnbound</pre>
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div><br class="table-break">
					<p>
						The following example statement specifies some of the built-in annotations in combination:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Name("RevenuePerCustomer")
@Description("Outputs revenue per customer considering all events encountered so far.")
@Tag(name="grouping", value="customer")

select customerId, sum(revenue) from CustomerRevenueEvent</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-name"></a>5.2.7.4. @Name</h4>
							</div>
						</div>
					</div>
					<p>
						Use the @Name EPL annotation to specify a statement name within the statement itself, as an alternative to specifying the statement name via API.
					</p>
					<p>
						If your application is also providing a statement name through the API, the statement name provided through the API overrides the annotation-provided statement name.
					</p>
					<p>
						Example:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Name("SecurityFilter1") select * from SecurityFilter(ip="127.0.0.1")</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-description"></a>5.2.7.5. @Description</h4>
							</div>
						</div>
					</div>
					<p>
						Use the @Description annotation to add a description text.
					</p>
					<p>
						Example:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Description('This statement filters localhost.') select * from SecurityFilter(ip="127.0.0.1")</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-tag"></a>5.2.7.6. @Tag</h4>
							</div>
						</div>
					</div>
					<p>
						Use the @Tag EPL annotation to tag statements with name-value pairs, effectively adding a property to the statement. The attributes <code class="literal">name</code> and <code class="literal">value</code> are of type string.
					</p>
					<p>
						Example:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Tag(name='ip_sensitive', value='Y') 
@Tag(name='author', value='Jim')
select * from SecurityFilter(ip="127.0.0.1")</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-priority"></a>5.2.7.7. @Priority</h4>
							</div>
						</div>
					</div>
					<p>
						This annotation only takes effect if the runtime-level setting for prioritized execution is set via configuration, as described in <a class="xref" href="configuration.html#configuration-runtime-execution" title="17.6.10. Runtime Settings Related to Execution of Statements">Section 17.6.10, “Runtime Settings Related to Execution of Statements”</a>.
					</p>
					<p>
						Use the @Priority EPL annotation to tag statements with a priority value. The default priority value is zero (0) for all statements. When an event (or single timer execution) requires processing the event for multiple statements, processing begins with the highest priority statement and ends with the lowest-priority statement.
					</p>
					<p>
						Example:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Priority(10) select * from SecurityFilter(ip="127.0.0.1")</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-drop"></a>5.2.7.8. @Drop</h4>
							</div>
						</div>
					</div>
					<p>
						This annotation only takes effect if the runtime-level setting for prioritized execution is set via configuration, as described in <a class="xref" href="configuration.html#configuration-runtime-execution" title="17.6.10. Runtime Settings Related to Execution of Statements">Section 17.6.10, “Runtime Settings Related to Execution of Statements”</a>.
					</p>
					<p>
						Use the @Drop EPL annotation to tag statements that preempt all other same or lower-priority statements. When an event (or single timer execution) requires processing the event for multiple statements, processing begins with the highest priority statement and ends with the first statement marked with @Drop, which becomes the last statement to process that event.
					</p>
					<p>
						Unless a different priority is specified, the statement with the @Drop EPL annotation executes at priority 1. Thereby @Drop alone is an effective means to remove events from a stream.
					</p>
					<p>
						Example:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Drop select * from SecurityFilter(ip="127.0.0.1")</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-hint"></a>5.2.7.9. @Hint</h4>
							</div>
						</div>
					</div>
					<p>
						A hint can be used to provide tips for the runtime to affect statement execution. Hints change performance or memory-use of a statement but generally do not change its output.
					</p>
					<p>
						The string value of a <code class="literal">Hint</code> annotation contains a keyword or a comma-separated list of multiple keywords. Hint keywords are case-insensitive. A list of hints is available in <a class="xref" href="performance.html#perf-tips-15" title="24.2.22. Consider Using Hints">Section 24.2.22, “Consider Using Hints”</a>.
					</p>
					<p>
						Example:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hint('disable_reclaim_group') 
select ipaddress, count(*) from SecurityFilter#time(60 sec) group by ipaddress</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-hook"></a>5.2.7.10. @Hook</h4>
							</div>
						</div>
					</div>
					<p>
						A hook is for attaching a callback to a statement.
					</p>
					<p>
						The type value of a <code class="literal">@Hook</code> annotation defines the type of hook and the <code class="literal">hook</code> value is an imported or fully-qualified class name providing the callback implementation.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-audit"></a>5.2.7.11. @Audit</h4>
							</div>
						</div>
					</div>
					<p>
						Causes the runtime to output detailed information about the statements processing. Described in more detail at <a class="xref" href="apicompiler.html#devlifecycle-debugging-audit" title="15.12.1. @Audit Annotation">Section 15.12.1, “@Audit Annotation”</a>.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-eventrepresentation"></a>5.2.7.12. @EventRepresentation</h4>
							</div>
						</div>
					</div>
					<p>
						Use the <code class="literal">@EventRepresentation</code> annotation with <code class="literal">create schema</code> and <code class="literal">create window</code> statements to instruct the compiler to use a specific event representation for the schema or named window.
					</p>
					<p>
						Use the <code class="literal">@EventRepresentation</code> annotation with <code class="literal">select</code> statements to instruct the compiler to use a specific event representation for output events.
					</p>
					<p>
						When no <code class="literal">@EventRepresentation</code> annotation is specified, the compiler uses the default event representation as configured, see <a class="xref" href="configuration.html#configuration-common-eventmeta-representation" title="17.4.9.1. Default Event Representation">Section 17.4.9.1, “Default Event Representation”</a>.
					</p>
					<p>
						Use <code class="literal">@EventRepresentation(objectarray)</code> to instruct the compiler to use object-array events.
					</p>
					<p>
						Use <code class="literal">@EventRepresentation(json)</code> to instruct the compiler to use JSON events.
					</p>
					<p>
						Use <code class="literal">@EventRepresentation(avro)</code> to instruct the compiler to use Avro events.
					</p>
					<p>
						Use <code class="literal">@EventRepresentation(map)</code> to instruct the compiler to use Map events.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-syntax-annotation-iterableunbound"></a>5.2.7.13. @IterableUnbound</h4>
							</div>
						</div>
					</div>
					<p>
						Causes the compiler, for statements with unbound streams, to retain the last event for the purpose of iterating using the iterator API. A compiler configuration is
						also available as described in <a class="xref" href="configuration.html#configuration-compiler-viewresources-iterableunbound" title="17.5.2.1. Iterator Behavior For Unbound Streams">Section 17.5.2.1, “Iterator Behavior For Unbound Streams”</a>.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-expression-alias"></a>5.2.8. Expression Alias</h3>
						</div>
					</div>
				</div><a id="d0e7267" class="indexterm"></a><a id="d0e7270" class="indexterm"></a>
				<p>
					An expression alias simply assigns a name to an expression. The alias name can be used in other expressions to refer to that expression, without the need to duplicate the expression.
				</p>
				<p>
					The expression alias obtains its scope from where it is used. Parameters cannot be provided.
					A second means to sharing expressions is the expression declaration as described next, which allows passing parameters and is more tightly scoped.
				</p>
				<p>
					A statement can contain and refer to any number of expression aliases.
					For expressions aliases that are visible across multiple statements please consult <a class="xref" href="epl_clauses.html#create-exprglobal-alias" title="5.18.1. Global Expression Aliases">Section 5.18.1, “Global Expression Aliases”</a>
					that explains the <code class="literal">create expression</code> clause.
				</p>
				<p>
					The syntax for an expression alias is:
				</p>
				<pre class="synopsis">expression <span class="emphasis"><em>expression_name</em></span> <code class="literal">alias for { </code><span class="emphasis"><em>expression</em></span> <code class="literal">}</code></pre>
				<p>
					An expression alias consists of the expression name and an expression in curly braces.
					The return type of the expression is determined by the compiler and need not be specified.
					The scope is automatic and determined by where the alias name is used therefore parameters cannot be specified.
				</p>
				<p>
					This example declares an expression alias <code class="literal">twoPI</code> that substitutes <code class="literal">Math.PI * 2</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression twoPI alias for { Math.PI * 2 }
select twoPI from SampleEvent</pre>
				<p>
					The next example specifies an alias <code class="literal">countPeople</code> and uses the alias in the <code class="literal">select</code>-clause and the <code class="literal">having</code>-clause:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression countPeople alias for { count(*) }
select countPeople from EnterRoomEvent#time(10 seconds) having countPeople &gt; 10</pre>
				<p>
					When using the expression alias in an expression, empty parentheses can optionally be specified. In the above example, <code class="literal">countPeople()</code> can be used instead and equivalently.
				</p>
				<p>
					The following scope rules apply for expression aliases:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Expression aliases do not remove implicit limitations: For example, aggregation functions cannot be used in a filter expression even if assigned an alias.
							</p>
						</li>
					</ol>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-expression-decl"></a>5.2.9. Expression Declaration</h3>
						</div>
					</div>
				</div><a id="d0e7339" class="indexterm"></a><a id="d0e7342" class="indexterm"></a>
				<p>
					A statement can contain expression declarations. Expressions that are common to multiple places in the same statement can be moved to a named expression declaration and reused within the same statement without duplicating the expression itself.
				</p>
				<p>
					For declaring expressions that are visible across multiple statements i.e. globally visible expressions please consult <a class="xref" href="epl_clauses.html#create-exprglobal-expr" title="5.18.2. Global Expression Declarations">Section 5.18.2, “Global Expression Declarations”</a>
					that explains the <code class="literal">create expression</code> clause.
				</p>
				<p>
					The runtime may cache declared expression result values and reuse cache values, see <a class="xref" href="configuration.html#configuration-runtime-execution-declaredexprvaluecachesize" title="17.6.10.6. Declared Expression Value Cache Size">Section 17.6.10.6, “Declared Expression Value Cache Size”</a>.
				</p>
				<p>
					An expression declaration follows the lambda-style expression syntax. This syntax was chosen as it typically allows for a shorter and more concise expression body that can be easier to read then most procedural code.
				</p>
				<p>
					The syntax for an expression declaration is:
				</p>
				<pre class="synopsis">expression <span class="emphasis"><em>expression_name</em></span> { <span class="emphasis"><em>expression_body</em></span> }</pre>
				<p>
					An expression declaration consists of the expression name and an expression body. The <span class="emphasis"><em>expression_name</em></span> is any identifier. The <span class="emphasis"><em>expression_body</em></span> contains optional parameters and the expression.
					The parameter types and the return type of the expression is determined by the compiler and do not need to be specified.
				</p>
				<p>
					Parameters to a declared expression can be:
				</p>
				<div class="itemizedlist">
					<ul>
						<li>
							<p>Any expression. For example <code class="literal">expression E {(v1,v2) =&gt; max(v1,v2)} select E(1, 2) from OrderItemEvent</code>.</p>
						</li>
						<li>
							<p>A stream name defined in the <code class="literal">from</code>-clause. For example <code class="literal">expression E {e =&gt; max(e.price,e.quote)} select E(o) from OrderItemEvent as o</code>.</p>
						</li>
						<li>
							<p>A pattern tag name. For example <code class="literal">expression E {e =&gt; max(e.price,e.quote)} select E(o) from pattern[timer:interval(10) or o=OrderItemEvent]</code>.</p>
						</li>
						<li>
							<p>A wildcard (<code class="literal">*</code>). For example <code class="literal">expression E {e =&gt; max(e.price,e.quote)} select E(*) from OrderItemEvent</code>.</p>
						</li>
					</ul>
				</div>
				<p>
					Use wildcard to pass the event itself to the expression. In a join or subquery, or more generally in an expression where multiple streams or pattern tags are available, the EPL must specify the stream name or pattern tag name and cannot use wildcard.
				</p>
				<p>
					In the expression body the <code class="literal">=&gt;</code> lambda operator reads as "goes to" (<code class="literal">-&gt;</code> may be used and is equivalent). The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression. The lambda expression <code class="literal">x =&gt; x * x</code> is read "x goes to x times x".
				</p>
				<p>
					In the expression body, if your expression takes no parameters, you may simply specify the expression and do not need the <code class="literal">=&gt;</code> lambda operator.
				</p>
				<p>
					If your expression takes one parameters, specify the input parameter name followed by the <code class="literal">=&gt;</code> lambda operator and followed by the expression. The synopsis for use with a single input parameter is:
				</p>
				<pre class="synopsis">expression_body:   <span class="emphasis"><em>input_param_name</em></span> =&gt; <span class="emphasis"><em>expression</em></span> </pre>
				<p>
					If your expression takes two or more parameters, specify the input parameter names in parenthesis followed by the <code class="literal">=&gt;</code> lambda operator followed by the expression. The synopsis for use with a multiple input parameter is:
				</p>
				<pre class="synopsis">expression_body:   (<span class="emphasis"><em>input_param</em></span> [,<span class="emphasis"><em>input_param</em></span> [,...]]) =&gt; <span class="emphasis"><em>expression</em></span> </pre>
				<p>
					The following example declares an expression that returns two times PI (ratio of the circumference of a circle to its diameter) and demonstrates its use in a select-clause:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression twoPI { Math.PI * 2} select twoPI() from SampleEvent</pre>
				<p>
					The parentheses are optional when the expression accepts no parameters. The below is equivalent to the previous example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression twoPI { Math.PI * 2} select twoPI from SampleEvent</pre>
				<p>
					The next example declares an expression that accepts one parameter: a MarketData event. The expression computes a new "mid" price based on the buy and sell price:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression midPrice { x =&gt; (x.buy + x.sell) / 2 } 
select midPrice(md) from MarketDataEvent as md</pre>
				<p>
					The variable name can be left off if event property names resolve without ambiguity.
				</p>
				<p>
					This example EPL removes the variable name <code class="literal">x</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression midPrice { x =&gt; (buy + sell) / 2 } 
select midPrice(md) from MarketDataEvent as md</pre>
				<p>
					The next example EPL specifies wildcard instead:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression midPrice { x =&gt; (buy + sell) / 2 } 
select midPrice(*) from MarketDataEvent</pre>
				<p>
					A further example that demonstrates two parameters is listed next. The example joins two streams and uses the price value from MarketDataEvent and the sentiment value of NewsEvent to compute a weighted sentiment:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression weightedSentiment { (x, y) =&gt; x.price * y.sentiment } 
select weightedSentiment(md, news) 
from MarketDataEvent#lastevent as md, NewsEvent#lastevent news</pre>
				<p>
					Any expression can be used in the expression body including aggregations, variables, subqueries or further declared or alias expressions. Sub-queries, when used without <code class="literal">in</code> or <code class="literal">exists</code>, must be placed within parenthesis.
				</p>
				<p>
					An example subquery within an expression declaration is shown next:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression newsSubq { md -&gt; 
    (select sentiment from NewsEvent#unique(symbol) where symbol = md.symbol) 
} 
select newsSubq(mdstream)
from MarketDataEvent mdstream</pre>
				<p>
					When using expression declarations please note these limitations:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Parameters to a declared expression can only be a stream name, pattern tag name or wildcard (<code class="literal">*</code>).
							</p>
						</li>
						<li>
							<p>
								Expression declarations do not remove implicit limitations: For example, aggregation functions cannot be used in a filter expression even if using an expression declaration.
							</p>
						</li>
					</ol>
				</div>
				<p>
					The following scope rules apply for declared expressions:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								The scope of the expression body of a declared expression only includes the parameters explicitly listed. Consider using an expression alias instead.
							</p>
						</li>
					</ol>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-class-decl"></a>5.2.10. Inlined-Class Declaration</h3>
						</div>
					</div>
				</div><a id="d0e7522" class="indexterm"></a>
				<p>
					EPL allows adding Java-language (C# for NEsper) class code directly into the EPL.
					Please see <a class="xref" href="inlinedclass.html" title="Chapter 18. Inlined Classes">Chapter 18, <i>Inlined Classes</i></a> for more information.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-script-decl"></a>5.2.11. Script Declaration</h3>
						</div>
					</div>
				</div><a id="d0e7532" class="indexterm"></a>
				<p>
					EPL allows the use of scripting languages. Any scripting language that supports JSR 223 and also the MVEL scripting language can be specified in EPL.
				</p>
				<p>
					Please see <a class="xref" href="script.html" title="Chapter 19. Script Support">Chapter 19, <i>Script Support</i></a> for more information.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-context-decl"></a>5.2.12. Referring to a Context</h3>
						</div>
					</div>
				</div>
				<p>
					You may refer to a context in the EPL text by specifying the <code class="literal">context</code> keyword followed by a context name. Context are described in more detail at <a class="xref" href="context.html" title="Chapter 4. Context and Context Partitions">Chapter 4, <i>Context and Context Partitions</i></a>
				</p>
				<p>
					The effect of referring to a context is that your statement operates according to the context dimensional information as declared for the context.
				</p>
				<p>
					The synopsis is:
				</p>
				<pre class="synopsis">... context <span class="emphasis"><em>context_name</em></span> ...</pre>
				<p>
					You may refer to a context in all statements except for the following types of statements:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								<code class="literal">create schema</code> for declaring event types.
							</p>
						</li>
						<li>
							<p>
								<code class="literal">create variable</code> for declaring a variable.
							</p>
						</li>
						<li>
							<p>
								<code class="literal">create index</code> for creating an index on a named window or table.
							</p>
						</li>
						<li>
							<p>
								<code class="literal">update istream</code> for updating insert stream events.
							</p>
						</li>
					</ol>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-compositekey"></a>5.2.13. Composite Keys and Array Values as Keys</h3>
						</div>
					</div>
				</div>
				<p>
					EPL allows composite keys that consist of two or more expressions (or fields or columns or more generally expressions) that identify an occurrence.
					EPL also allows keys to be of type array.
				</p>
				<p>
					This is applicable in each place there is an opportunity to provide key expressions. It is thus applicable to the <code class="literal">group-by</code> clause including <code class="literal">rollup</code>, data windows with keys (such as <code class="literal">#unique</code>, <code class="literal">#firstunique</code>, <code class="literal">#groupwin</code>, <code class="literal">#rank</code>), <code class="literal">partition-by</code> for keyed segmented contexts, contexts with <code class="literal">distinct</code>, the select-clause <code class="literal">distinct</code> keyword, the query planner when planning implicit and explicit indexes, <code class="literal">create index</code>, <code class="literal">every-distinct</code>, the <code class="literal">partition-by</code> clause for match-recognize, table column keyed-access expressions, the <code class="literal">for</code>-clause for grouped delivery and the <code class="literal">distinctOf</code> enumeration method as well as the <code class="literal">distinct</code> keyword for aggregation functions.
				</p>
				<p>
					For expressions returning array of primitive the compiler uses <code class="literal">Arrays.hashCode</code> and <code class="literal">Arrays.equals</code>.
					For expressions returning array of object the compiler uses <code class="literal">Arrays.deepHashCode</code> and <code class="literal">Arrays.deepEquals</code>.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-select-list"></a>5.3. Choosing Event Properties and Events: The <span class="emphasis"><em>Select</em></span> Clause</h2>
					</div>
				</div>
			</div><a id="d0e7659" class="indexterm"></a><a id="d0e7662" class="indexterm"></a>
			<p>
				The <code class="literal">select</code> clause is required in all statements. The <code class="literal">select</code> clause can be used to select all properties via the wildcard <code class="literal">*</code>, or to specify a list of event properties and expressions. The <code class="literal">select</code> clause defines the event type (event property names and types) of the resulting events published by the statement, or pulled from the statement via the iterator methods.
			</p>
			<p>
				The <code class="literal">select</code> clause also offers optional <code class="literal">istream</code>, <code class="literal">irstream</code> and <code class="literal">rstream</code> keywords to control whether input stream, remove stream or input and remove stream events are posted to <code class="literal">UpdateListener</code> instances and observers to a statement. By default, the runtime provides only the insert stream to listener and observers. See <a class="xref" href="configuration.html#configuration-compiler-streamselection" title="17.5.4. Compiler Settings Related to Stream Selection">Section 17.5.4, “Compiler Settings Related to Stream Selection”</a> on how to change the default.
			</p>
			<p>
				The syntax for the <code class="literal">select</code> clause is summarized below.
			</p>
			<pre class="synopsis">select [istream | irstream | rstream] [distinct] * | <span class="emphasis"><em>expression_list</em></span> ... </pre>
			<p>
				The <code class="literal">istream</code> keyword is the default, and indicates that the runtime only delivers insert stream events to listeners and observers. The <code class="literal">irstream</code> keyword indicates that the runtime delivers both insert and remove stream. Finally, the <code class="literal">rstream</code> keyword tells the runtime to deliver only the remove stream.
			</p>
			<p>
				The <code class="literal">distinct</code> keyword outputs only unique rows depending on the column list you have specified after it. It must occur after the <code class="literal">select</code> and after the optional stream keywords, as described in more detail below.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-select-all-props"></a>5.3.1. Choosing the Event Itself: Select *</h3>
						</div>
					</div>
				</div>
				<p>
					The syntax for selecting the event itself is:
				</p>
				<pre class="synopsis">select * from <span class="emphasis"><em>stream_def</em></span></pre>
				<p>
					The following statement selects StockTick events for the last 30 seconds of IBM stock ticks.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from StockTick(symbol='IBM')#time(30 sec)</pre>
				<p>
					You may well be asking: Why does the statement specify a time window here? First, the statement is meant to demonstrate the use of <code class="literal">*</code> wildcard.
					When the runtime pushes statement results to your listener and as the statement does not select remove stream events via <code class="literal">rstream</code> keyword, the listener receives only new events and the time window could be left off.
					By adding the time window the pull API (iterator API or JDBC driver) returns the last 30 seconds of events.
				</p>
				<p>
					The <code class="literal">*</code> wildcard and expressions can also be combined in a <code class="literal">select</code> clause. The combination selects all event properties and in addition the computed values
					as specified by any additional expressions that are part of the <code class="literal">select</code> clause. Here is an example that selects all properties of stock tick events plus a computed product of price and volume that the
					statement names 'pricevolume':
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select *, price * volume as pricevolume from StockTick</pre>
				<p>
					When using wildcard (*), the runtime does not actually read or copy your event properties out of your event or events, neither does it copy the event object.
					It simply wraps your native type in an <code class="literal">EventBean</code> interface. Your application has access to
					the underlying event object through the <code class="literal">getUnderlying</code> method and has access to the property values through the <code class="literal">get</code> method.
				</p>
				<p>
					In a join statement, using the <code class="literal">select *</code> syntax selects one event property per stream to hold the event for that stream. The property name is the stream name in the <code class="literal">from</code> clause.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-select-event-props"></a>5.3.2. Choosing Specific Event Properties</h3>
						</div>
					</div>
				</div>
				<p>
					To choose the particular event properties to return:
				</p>
				<pre class="synopsis">select <span class="emphasis"><em>event_property</em></span> [, <span class="emphasis"><em>event_property</em></span>] [, ...] from <span class="emphasis"><em>stream_def</em></span></pre>
				<p>
					The following statement simply selects the symbol and price properties of stock ticks, and the total volume for stock tick events in a 60-second time window.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, price, sum(volume) from StockTick(symbol='IBM')#time(60 sec)
</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-select-expressions"></a>5.3.3. Expressions</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">select</code> clause can contain one or more expressions.
				</p>
				<pre class="synopsis">select <span class="emphasis"><em>expression</em></span> [, <span class="emphasis"><em>expression</em></span>] [, ...] from <span class="emphasis"><em>stream_def</em></span></pre>
				<p>
					The following statement selects the volume multiplied by price for a time batch of the last 30 seconds of stock tick events.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select volume * price from StockTick#time_batch(30 sec)</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-select-renaming"></a>5.3.4. Renaming Event Properties</h3>
						</div>
					</div>
				</div>
				<p>
					Event properties and expressions can be renamed using below syntax.
				</p>
				<pre class="synopsis">select [<span class="emphasis"><em>event_property</em></span> | <span class="emphasis"><em>expression</em></span>] [as] <span class="emphasis"><em>identifier</em></span> [, ...]</pre>
				<p>
					The following statement selects volume multiplied by price and specifies the name <span class="emphasis"><em>volPrice</em></span> for the resulting column.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select volume * price as volPrice from StockTick</pre>
				<p>
					Identifiers cannot contain the "." (dot) character, i.e. "vol.price" is not a valid identifier for the rename syntax.
				</p>
				<p>
					The <code class="literal">as</code> keyword is optional. The following EPL is therefore equivalent to above:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select volume * price volPrice from StockTick</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-select-all-join"></a>5.3.5. Choosing Event Properties and Events in a Join</h3>
						</div>
					</div>
				</div>
				<p>
					If your statement is joining multiple streams, your may specify property names that are unique among the joined streams, or use wildcard (*) as explained earlier.
				</p>
				<p>
					In case the property name in your <code class="literal">select</code> or other clauses is not unique considering all joined streams, you will need to use the name of the stream as a prefix to the property.
				</p>
				<p>
					This example is a join between the two streams StockTick and News, respectively named as 'tick' and 'news'. The example selects from the StockTick event the symbol value using the 'tick' stream name as a prefix:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select tick.symbol from StockTick#time(10) as tick, News#time(10) as news
where news.symbol = tick.symbol</pre>
				<p>
					Use the wildcard (*) selector in a join to generate a property for each stream, with the property value being the event itself. The output events of the statement below have two properties: the 'tick' property holds the StockTick event and the 'news' property holds the News event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from StockTick#time(10) as tick, News#time(10) as news</pre>
				<p>
					The following syntax can also be used to specify what stream's properties to select:
				</p>
				<pre class="synopsis">select <span class="emphasis"><em>stream_name</em></span>.* [as <span class="emphasis"><em>name</em></span>] from ...</pre>
				<p>
					The selection of <code class="literal">tick.*</code> selects the StockTick stream events only:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select tick.* from StockTick#time(10) as tick, News#time(10) as news
where tick.symbol = news.symbol</pre>
				<p>
					The next example uses the <code class="literal">as</code> keyword to name each stream's joined events. This instructs the compiler to create a property for each named event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select tick.* as stocktick, news.* as news 
from StockTick#time(10) as tick, News#time(10) as news
where stock.symbol = news.symbol</pre>
				<p>
					The output events of the above example have two properties 'stocktick' and 'news' that are the StockTick and News events.
				</p>
				<p>
					The stream name itself, as further described in <a class="xref" href="epl_clauses.html#epl-from-clause-stream-name" title="5.4.5. Using the Stream Name">Section 5.4.5, “Using the Stream Name”</a>, may be used within expressions or alone.
				</p>
				<p>
					This example passes events to a user-defined function named <code class="literal">compute</code> and also shows <code class="literal">insert-into</code> to populate an event stream of combined events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into TickNewStream select tick, news, MyLib.compute(news, tick) as result
from StockTick#time(10) as tick, News#time(10) as news
where tick.symbol = news.symbol</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// second statement that uses the TickNewStream stream
select tick.price, news.text, result from TickNewStream</pre>
				<p>
					In summary, the <span class="emphasis"><em>stream_name.*</em></span> streamname wildcard syntax can be used to select a stream as the underlying event or as a property, but cannot appear within an expression. While the <span class="emphasis"><em>stream_name</em></span> syntax (without wildcard) always selects a property (and not as an underlying event), and can occur anywhere within an expression.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-select-pattern"></a>5.3.6. Choosing Event Properties and Events From a Pattern</h3>
						</div>
					</div>
				</div>
				<p>
					If your statement employs pattern expressions, then your pattern expression tags events with a tag name. Each tag name becomes available for use as a property in the <code class="literal">select</code> clause and all other clauses.
				</p>
				<p>
					For example, here is a very simple pattern that matches on every StockTick event received within 30 seconds after start of the statement. The sample selects the symbol and price properties of the matching events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select tick.symbol as symbol, tick.price as price
from pattern[every tick=StockTick where timer:within(10 sec)]</pre>
				<p>
					The use of the wildcard selector, as shown in the next statement, creates a property for each tagged event in the output. The next statement outputs events that hold a single 'tick' property whose value is the event itself:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from pattern[every tick=StockTick where timer:within(10 sec)]</pre>
				<p>
					You may also select the matching event itself using the <code class="literal">tick.*</code> syntax. The runtime outputs the StockTick event itself to listeners:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select tick.* from pattern[every tick=StockTick where timer:within(10 sec)]</pre>
				<p>
					A tag name as specified in a pattern is a valid expression itself. This example uses the <code class="literal">insert into</code> clause to make available the events matched by a pattern to further statements:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// make a new stream of ticks and news available
insert into StockTickAndNews 
select tick, news from pattern [every tick=StockTick -&gt; news=News(symbol=tick.symbol)]</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// second statement to select from the stream of ticks and news
select tick.symbol, tick.price, news.text from StockTickAndNews</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-select-using-istream-rstream"></a>5.3.7. Selecting <code class="literal">Insert</code> and <code class="literal">Remove</code> Stream Events</h3>
						</div>
					</div>
				</div>
				<p>
					The optional <code class="literal">istream</code>, <code class="literal">irstream</code> and <code class="literal">rstream</code> keywords in the <code class="literal">select</code> clause control the event streams posted to listeners and observers to a statement.
				</p>
				<p>
					If neither keyword is specified, and in the default configuration, the runtime posts only
					insert stream events via the <code class="literal">newEvents</code> parameter to the <code class="literal">update</code> method of <code class="literal">UpdateListener</code> instances listening to
					the statement. The runtime does not post remove stream events, by default.
				</p>
				<p>
					The insert stream consists of the events entering the respective window(s) or stream(s) or aggregations, while the remove stream consists of the events leaving the respective window(s) or the changed aggregation result.
					See <a class="xref" href="processingmodel.html" title="Chapter 2. Basic Concepts">Chapter 2, <i>Basic Concepts</i></a> for more information on insert and remove streams.
				</p>
				<p>
					The runtime posts remove stream events to the <code class="literal">oldEvents</code> parameter of the <code class="literal">update</code> method only if the <code class="literal">irstream</code> keyword
					occurs in the <code class="literal">select</code> clause. This behavior can be changed via configuration as described in <a class="xref" href="configuration.html#configuration-compiler-streamselection" title="17.5.4. Compiler Settings Related to Stream Selection">Section 17.5.4, “Compiler Settings Related to Stream Selection”</a>.
				</p>
				<p>
					By specifying the <code class="literal">istream</code> keyword you can instruct the runtime to only post insert stream events via the <code class="literal">newEvents</code> parameter to the <code class="literal">update</code> method on listeners. The runtime will then not post any remove stream events, and the <code class="literal">oldEvents</code> parameter is always a null value.
				</p>
				<p>
					By specifying the <code class="literal">irstream</code> keyword you can instruct the runtime to post both insert stream and remove stream events.
				</p>
				<p>
					By specifying the <code class="literal">rstream</code> keyword you can instruct the runtime to only post remove stream events via the <code class="literal">newEvents</code> parameter to the <code class="literal">update</code> method on listeners. The runtime will then not post any insert stream events, and the <code class="literal">oldEvents</code> parameter is also always a null value.
				</p>
				<p>
					The following statement selects only the events that are leaving the 30 second time window.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select rstream * from StockTick#time(30 sec)</pre>
				<p>
					The <code class="literal">istream</code> and <code class="literal">rstream</code> keywords in the <code class="literal">select</code> clause are matched by same-name keywords available in the <code class="literal">insert into</code> clause. While the keywords in the <code class="literal">select</code> clause control the event stream posted to listeners to the statement, the same keywords in the <code class="literal">insert into</code> clause specify the event stream that the runtime makes available to other statements.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-syntax-distinct"></a>5.3.8. Select <code class="literal">Distinct</code></h3>
						</div>
					</div>
				</div>
				<p>
					The optional <code class="literal">distinct</code> keyword removes duplicate output events from output. The keyword must occur after the <code class="literal">select</code> keyword and after the optional <code class="literal">irstream</code> keyword.
				</p>
				<p>
					The <code class="literal">distinct</code> keyword in your <code class="literal">select</code> instructs the runtime to consolidate, at time of output, the output event(s) and remove output events with identical property values.
					Duplicate removal only takes place when two or more events are output together at any one time, therefore <code class="literal">distinct</code> is typically used with a batch data window, output rate limiting, fire-and-forget queries, on-select or iterator pull API.
				</p>
				<p>
					If two or more output event objects have same property values for all properties of the event, the <code class="literal">distinct</code> removes all but one duplicated event before outputting events to listeners. Indexed, nested and mapped properties
					are considered in the comparison, if present in the output event. Further detail on key expressions can be found at <a class="xref" href="epl_clauses.html#epl-syntax-compositekey" title="5.2.13. Composite Keys and Array Values as Keys">Section 5.2.13, “Composite Keys and Array Values as Keys”</a>.
				</p>
				<p>
					The next example outputs sensor ids of temperature sensor events, but only every 10 seconds and only unique sensor id values during the 10 seconds:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select distinct sensorId from TemperatureSensorEvent output every 10 seconds</pre>
				<p>
					Use <code class="literal">distinct</code> with wildcard (<code class="literal">*</code>) to remove duplicate output events considering all properties of an event.
				</p>
				<p>
					This example statement outputs all distinct events either when 100 events arrive or when 10 seconds passed, whichever occurs first:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select distinct * from TemperatureSensorEvent#time_length_batch(10, 100)</pre>
				<p>
					When selecting nested, indexed, mapped or dynamic properties in a <code class="literal">select</code> clause with <code class="literal">distinct</code>, it is relevant to know that the comparison uses hash code and the Java <code class="literal">equals</code> semantics.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-transposefunc"></a>5.3.9. Transposing an Expression Result to a Stream</h3>
						</div>
					</div>
				</div>
				<p>
					For transposing an instance of a Java object returned by an expression to a stream use the transpose function as described in <a class="xref" href="functionreference.html#functionreference-transpose" title="10.4. Select-Clause Transpose Function">Section 10.4, “Select-Clause Transpose Function”</a>.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-selecteventbean"></a>5.3.10. Selecting EventBean Instead of Underlying Event</h3>
						</div>
					</div>
				</div>
				<p>
					By default, for certain select-clause expressions that output events or a collection of events,
					the runtime outputs the underlying event objects. The term <span class="emphasis"><em>outputs</em></span> means the data passed to listeners,
					subscribers and inserted-into into another stream via insert-into.
				</p>
				<p>
					The select-clause expressions for which underlying event objects are output by default are:
				</p>
				<div class="itemizedlist">
					<ul>
						<li>
							Event Aggregation Functions (including extension API)
						</li>
						<li>
							The <code class="literal">previous</code> family of single-row functions
						</li>
						<li>
							Subselects that select events
						</li>
						<li>
							Declared expressions and enumeration methods that operate on any of the above
						</li>
					</ul>
				</div>
				<p>
					To have the runtime output <code class="literal">EventBean</code> instance(s) instead, add <code class="literal">@eventbean</code>
					to the relevant expressions of the <code class="literal">select</code>-clause.
				</p>
				<p>
					The sample EPL shown below outputs current data window contents as <code class="literal">EventBean</code> instances
					into the stream <code class="literal">OutStream</code>, thereby statements consuming the stream may operate on such instances:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into OutStream 
select prevwindow(s0) @eventbean as win 
from MyEvent#length(2) as s0</pre>
				<p>
					The next EPL consumes the stream and selects the last event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select win.lastOf() from OutStream</pre>
				<p>
					It is not necessary to use <code class="literal">@eventbean</code> if an event type by the same name (<code class="literal">OutStream</code> in the example) is already declared
					and a property exist on the type by the same name (<code class="literal">win</code> in this example) and the type of the property is the event type (<code class="literal">MyEvent</code> in the example)
					returned by the expression. This is further described in <a class="xref" href="epl_clauses.html#insert-into-reconcile" title="5.10.8. Select-Clause Expression and Inserted-Into Column Event Type">Section 5.10.8, “Select-Clause Expression and Inserted-Into Column Event Type”</a>.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-from-clause"></a>5.4. Specifying Event Streams: The <span class="emphasis"><em>From</em></span> Clause</h2>
					</div>
				</div>
			</div><a id="d0e8203" class="indexterm"></a><a id="d0e8208" class="indexterm"></a><a id="d0e8211" class="indexterm"></a>
			<p>
				The <code class="literal">from</code> clause is required in all statements. It specifies one or more event streams, named windows or tables. Each event stream, named window or table can optionally be given a name by means of the <code class="literal">as</code> keyword.
			</p>
			<pre class="synopsis">from <span class="emphasis"><em>stream_def</em></span> [as <span class="emphasis"><em>name</em></span>] [unidirectional] [retain-union | retain-intersection] 
    [, <span class="emphasis"><em>stream_def</em></span> [as <span class="emphasis"><em>stream_name</em></span>]] [, ...]</pre>
			<p>
				The event stream definition <span class="emphasis"><em>stream_def</em></span> as shown in the syntax above can consists of either a filter-based event stream definition or a pattern-based event stream definition.
			</p>
			<p>
				For joins and outer joins, specify two or more event streams. Joins and the <code class="literal">unidirectional</code> keyword are described in more detail in <a class="xref" href="epl_clauses.html#epl-join" title="5.12. Joining Event Streams">Section 5.12, “Joining Event Streams”</a>.
				Joins are handy when multiple streams or patterns can trigger output and outer joins can be used to union and connect streams via <code class="literal">or</code>.
			</p>
			<p>
				EPL supports joins against relational databases for access to historical or reference data as explained in <a class="xref" href="epl_clauses.html#histdata_overview" title="5.13. Accessing Relational Data via SQL">Section 5.13, “Accessing Relational Data via SQL”</a>. EPL can also join results returned by an arbitrary invocation, as discussed in <a class="xref" href="epl_clauses.html#joining_method" title="5.14. Accessing Non-Relational Data via Method, Script or UDF Invocation">Section 5.14, “Accessing Non-Relational Data via Method, Script or UDF Invocation”</a>.
			</p>
			<p>
				The <span class="emphasis"><em>stream_name</em></span> is an optional identifier assigned to the stream. The stream name can itself occur in any expression and provides access to the event itself from the named stream. Also, a stream name may be combined with a method name to invoke instance methods on events of that stream.
			</p>
			<p>
				For all streams with the exception of historical sources your statement may employ data windows as outlined below. The <code class="literal">retain-intersection</code> (the default) and <code class="literal">retain-union</code> keywords build a union or intersection of two or more data windows as described in <a class="xref" href="epl_clauses.html#epl-from-clause-view-multidatawindow" title="5.4.4. Multiple Data Windows">Section 5.4.4, “Multiple Data Windows”</a>.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-from-clause-filter"></a>5.4.1. Filter-Based Event Streams</h3>
						</div>
					</div>
				</div>
				<p>
					The <span class="emphasis"><em>stream_def</em></span> syntax for a filter-based event stream is as below:
				</p>
				<pre class="synopsis"><span class="emphasis"><em>event_stream_name</em></span> [(<span class="emphasis"><em>filter_criteria</em></span>)] [<span class="emphasis"><em>contained_selection</em></span>] [#<span class="emphasis"><em>window_spec</em></span>] [#<span class="emphasis"><em>window_spec</em></span>] [...]</pre>
				<p>
					The <span class="emphasis"><em>event_stream_name</em></span> is either the name of an event type or name of an event stream populated by an <code class="literal">insert into</code> statement
					or the name of a named window or table.
				</p>
				<p>
					The <span class="emphasis"><em>filter_criteria</em></span> is optional and consists of a list of expressions filtering the events of the event stream, within parenthesis after the event stream name.
					Filter criteria cannot be specified for tables.
				</p>
				<p>
					The <span class="emphasis"><em>contained_selection</em></span> is optional and is for use with coarse-grained events that have properties that are themselves one or more events, see <a class="xref" href="epl_clauses.html#epl-containedeventselect" title="5.19. Contained-Event Selection">Section 5.19, “Contained-Event Selection”</a> for the synopsis and examples.
					Contained-event cannot be specified for tables.
				</p>
				<p>
					The <span class="emphasis"><em>window_spec</em></span> specify one or more data windows.
					Data windows cannot be specified for named windows and tables. Instead of the <code class="literal">#</code> hash character the <code class="literal">.</code> dot character can also be used, however the dot character requires the data window namespace.
				</p>
				<p>
					The following statement shows event type, filter criteria and data windows combined in one statement. It selects all event properties for the last 100 events of IBM stock ticks for volume. In the example, the event type is <code class="literal">StockTick</code>. The expression filters for events where the property <code class="literal">symbol</code> has a value of "IBM". This statement specifies a length window and thus computes the total volume of the last 100 events.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(volume) from StockTick(symbol='IBM')#length(100)</pre>
				<p>
					The runtime filters out events in an event stream as defined by filter criteria that are placed in parenthesis, before it sends events to the data window(s) (if any). Thus, compared to search conditions in a <code class="literal">where</code> clause, filter criteria remove unneeded events early. In the above example, events with a symbol other than IBM do not enter the length window.
				</p>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-filter-event-type"></a>5.4.1.1. Specifying an Event Type</h4>
							</div>
						</div>
					</div>
					<p>
						The simplest form of filter is a filter for events of a given type without any conditions on the event property values. This filter matches any event of that type regardless of the event's properties. The example below is such a filter.
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent</pre>
					<p>
						Instead of the fully-qualified Java class name any other event name can be mapped via Configuration to a Java class, making the resulting statement more readable:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent</pre>
					<p>
						Interfaces and superclasses are also supported as event types. In the below example <code class="literal">IRfidReadable</code> is an interface class.
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from org.myorg.rfid.IRfidReadable</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-filter-criteria"></a>5.4.1.2. Specifying Filter Criteria</h4>
							</div>
						</div>
					</div>
					<p>
						The filtering criteria to filter for events with certain event property values are placed within parenthesis after the event type name:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent(category="Perishable")</pre>
					<p>
						All expressions can be used in filters, including static methods that return a boolean value:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent(MyRFIDLib.isInRange(x, y) or (x &lt; 0 and y &lt; 0))</pre>
					<p>
						Filter expressions can be separated via a single comma '<code class="literal">,</code>'. The comma represents a logical AND between filter expressions:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent(zone=1, category=10)
...is equivalent to...
select * from RfidEvent(zone=1 and category=10)</pre>
					<p>
						The compiler analyzes the filter expressions and determines the filter indexes. This process is futher described at <a class="xref" href="apicompiler.html#apicompiler-filterplan" title="15.18. Compiler Filter Expression Analysis">Section 15.18, “Compiler Filter Expression Analysis”</a>. The runtime uses the compiler output to build, maintain and use filter indexes, please see <a class="xref" href="processingmodel.html#processingmodel_indexes_filterindexes" title="2.18.2. Filter Indexes">Section 2.18.2, “Filter Indexes”</a>. The compiler can translate the following operators, including combinations of these operators connected via <code class="literal">and</code> and <code class="literal">or</code>, into filter indexes:
					</p>
					<div class="itemizedlist">
						<ul compact="compact">
							<li>
								<p>
									equals <code class="literal">=</code>
								</p>
							</li>
							<li>
								<p>
									not equals <code class="literal">!=</code>
								</p>
							</li>
							<li>
								<p>
									comparison operators <code class="literal">&lt; , &gt; , &gt;=, &lt;=</code>
								</p>
							</li>
							<li>
								<p>
									ranges
								</p>
								<div class="itemizedlist">
									<ul compact="compact">
										<li>
											<p>
												use the <code class="literal">between</code> keyword for a closed range where both endpoints are included
											</p>
										</li>
										<li>
											<p>
												use the <code class="literal">in </code> keyword and round <code class="literal">()</code> or square brackets <code class="literal">[]</code> to control how endpoints are included
											</p>
										</li>
										<li>
											<p>
												for inverted ranges use the <code class="literal">not</code> keyword and the <code class="literal">between</code> or <code class="literal">in</code> keywords
											</p>
										</li>
									</ul>
								</div>
							</li>
							<li>
								<p>
									list-of-values checks using the <code class="literal">in</code> keyword or the <code class="literal">not in </code> keywords followed by a comma-separated list of values
								</p>
							</li>
							<li>
								<p>
									single-row functions that have been registered and are invoked via function name (see user-defined functions) and that either return a boolean value or that have their return value compared to a constant
								</p>
							</li>
							<li>
								<p>
									the <code class="literal">and</code> and <code class="literal">or</code> logical operators
								</p>
							</li>
						</ul>
					</div>
					<p>
						At compile time the compiler scans filter expressions for sub-expressions that can be placed into filter indexes. Indexing filter values to match event properties of incoming events enables the runtime to match incoming events faster, especially if your application creates a large number of statements or context partitions or requires many similar filters. The use of comma or logical <code class="literal">and</code> in filter expressions is fully equivalent.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-filter-ranges"></a>5.4.1.3. Filtering Ranges</h4>
							</div>
						</div>
					</div>
					<p>
						Ranges come in the following 4 varieties. The use of round <code class="literal">()</code>
						or square <code class="literal">[]</code> bracket dictates whether an endpoint is included or excluded. The low point and the high-point of the range are separated by the colon <code class="literal">:</code> character.
					</p>
					<div class="itemizedlist">
						<ul compact="compact">
							<li>
								<p>
									Open ranges that contain neither endpoint <code class="literal">(low:high)</code>
								</p>
							</li>
							<li>
								<p>
									Closed ranges that contain both endpoints <code class="literal">[low:high]</code>. The equivalent 'between' keyword also defines a closed range.
								</p>
							</li>
							<li>
								<p>
									Half-open ranges that contain the low endpoint but not the high endpoint <code class="literal">[low:high)</code>
								</p>
							</li>
							<li>
								<p>
									Half-closed ranges that contain the high endpoint but not the low endpoint <code class="literal">(low:high]</code>
								</p>
							</li>
						</ul>
					</div>
					<p>
						The next statement shows a filter specifying a range for <code class="literal">x</code> and <code class="literal">y</code> values of RFID events. The range includes both endpoints therefore uses <code class="literal">[]</code> hard brackets.
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">mypackage.RfidEvent(x in [100:200], y in [0:100])</pre>
					<p>
						The <code class="literal">between</code> keyword is equivalent for closed ranges. The same filter using the <code class="literal">between</code> keyword is:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">mypackage.RfidEvent(x between 100 and 200, y between 0 and 50)</pre>
					<p>
						The <code class="literal">not</code> keyword can be used to determine if a value falls outside a given range:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">mypackage.RfidEvent(x not in [0:100])</pre>
					<p>
						The equivalent statement using the <code class="literal">between</code> keyword is:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">mypackage.RfidEvent(x not between 0 and 100)</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-filter-in"></a>5.4.1.4. Filtering Sets of Values</h4>
							</div>
						</div>
					</div>
					<p>
						The <code class="literal">in</code> keyword for filter criteria determines if a given value matches any value in a list of values.
					</p>
					<p>
						In this example you are interested in RFID events where the category matches any of the given values:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">mypackage.RfidEvent(category in ('Perishable', 'Container'))</pre>
					<p>
						By using the <code class="literal">not in </code>keywords you can filter events with a property value that does not match any of the values in a list of values:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">mypackage.RfidEvent(category not in ('Household', 'Electrical'))</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-filter-limitations"></a>5.4.1.5. Filter Limitations</h4>
							</div>
						</div>
					</div>
					<p>
						The following restrictions apply to filter criteria:
					</p>
					<div class="itemizedlist">
						<ul compact="compact">
							<li>
								<p>
									Range and comparison operators require the event property to be of a numeric or string type.
								</p>
							</li>
							<li>
								<p>
									Aggregation functions are not allowed within filter expressions.
								</p>
							</li>
							<li>
								<p>
									The <code class="literal">prev</code> previous event function and the <code class="literal">prior</code> prior event function cannot be used in filter expressions.
								</p>
							</li>
						</ul>
					</div>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-from-clause-patterns"></a>5.4.2. Pattern-Based Event Streams</h3>
						</div>
					</div>
				</div>
				<p>
					Event pattern expressions can also be used to specify one or more event streams in a statement.
					For pattern-based event streams, the event stream definition <span class="emphasis"><em>stream_def</em></span> consists of the keyword <code class="literal">pattern</code> and a pattern expression in brackets <code class="literal">[]</code>. The syntax for an event stream definition using a pattern expression is below. As in filter-based event streams you can specify data windows.
				</p>
				<pre class="synopsis">pattern [<span class="emphasis"><em>pattern_expression</em></span>] [#<span class="emphasis"><em>window_spec</em></span>] [#<span class="emphasis"><em>window_spec</em></span>] [...]</pre>
				<p>
					The next statement specifies an event stream that consists of both stock tick events and trade events. The example tags stock tick events with the name "tick" and trade events with the name "trade".
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from pattern [every tick=StockTickEvent or every trade=TradeEvent]</pre>
				<p>
					This statement generates an event every time the runtime receives either one of the event types. The generated events resemble a map with "tick" and "trade" keys. For stock tick events, the "tick" key value is the underlying stock tick event, and the "trade" key value is a null value. For trade events, the "trade" key value is the underlying trade event, and the "tick" key value is a null value.
				</p>
				<p>
					Lets further refine this statement adding a data window the gives us the last 30 seconds of either stock tick or trade events. Lets also select prices and a price total.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select tick.price as tickPrice, trade.price as tradePrice, 
       sum(tick.price) + sum(trade.price) as total
  from pattern [every tick=StockTickEvent or every trade=TradeEvent]#time(30 sec)</pre>
				<p>
					Note that in the statement above <code class="literal">tickPrice</code> and <code class="literal">tradePrice</code> can each be null values depending on the event processed. Therefore, an aggregation function such as <code class="literal">sum(tick.price + trade.price))</code> would always return null values as either of the two price properties are always a null value for any event matching the pattern. Use the <code class="literal">coalesce</code> function to handle null values, for example: <code class="literal">sum(coalesce(tick.price, 0) + coalesce(trade.price, 0))</code>.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						When used with patterns, specifying a data window defines what pattern matches to retain in memory for the purpose of joins or for using the iterator API.
					</p>
					<p>
						When used with patterns, specifying a data window does not limit pattern matches to events in the window. The <code class="literal">match_recognize</code> pattern matching however does limit matches to events retained by a data window.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-from-clause-window-spec"></a>5.4.3. Specifying Data Windows</h3>
						</div>
					</div>
				</div>
				<p>
					Data windows retain a subset of events. They provide an retain/expiry policy for events and the runtime automatically removes events according to the retain/expiry policy. Data windows can be grouped and data windows can be intersected or unioned. See the section <a class="xref" href="epl-views.html" title="Chapter 14. EPL Reference: Data Windows">Chapter 14, <i>EPL Reference: Data Windows</i></a> on the data windows available. Data windows can take parameters. Any expressions can be a parameter, with limitations.
				</p>
				<p>
					The example statement below outputs a count per expressway for car location events (contains information about the location of a car on a highway) of the last 60 seconds:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select expressway, count(*) from CarLocEvent#time(60) 
group by expressway</pre>
				<p>
					The next example declares <code class="literal">#groupwin</code> and a <code class="literal">#length</code> window to indicate that there is a separate length window per car id:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select cardId, expressway, direction, segment, count(*) 
from CarLocEvent#groupwin(carId)#length(4) 
group by carId, expressway, direction, segment</pre>
				<p>
					The <code class="literal">#groupwin(carId)</code> groups car location events by car id. The <code class="literal">#length(4)</code> keeps a length window of the 4 last events, with one separate length window for each car id.
					The example reports the number of events per car id and per expressway, direction and segment considering the last 4 events for each car id only.
				</p>
				<p>
					The special keep-all window keeps all events: It does not expire events and does not provide a remove stream, i.e. events are not removed from the keep-all window unless by means of <code class="literal">on-delete</code> or <code class="literal">on-merge</code> or fire-and-forget <code class="literal">delete</code>.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-from-clause-view-multidatawindow"></a>5.4.4. Multiple Data Windows</h3>
						</div>
					</div>
				</div>
				<p>
					Data windows provide an expiry policy that indicates when to remove events from the data window, with the exception of the keep-all data window which has no expiry policy and the <code class="literal">#groupwin</code> grouped-window for allocating a new data window per group.
				</p>
				<p>
					EPL allows the freedom to use multiple data windows onto a stream and thus combine expiry policies. Combining data windows into an intersection (the default) or a union can achieve a useful strategy for retaining events and expiring events that are no longer of interest. Named windows, tables and <code class="literal">on-merge</code> and <code class="literal">on-delete</code> provide an additional degree of freedom.
				</p>
				<p>
					In order to combine two or more data windows there is no keyword required. The <span class="emphasis"><em>retain-intersection</em></span> keyword is the default and the <span class="emphasis"><em>retain-union</em></span> keyword may instead be provided for a stream.
				</p>
				<p>
					The concept of union and intersection come from Set mathematics. In the language of Set mathematics, two sets A and B can be "added" together: The intersection of A and B is the set of all things which are members of both A and B, i.e. the members two sets have "in common". The union of A and B is the set of all things which are members of either A or B.
				</p>
				<p>
					Use the <span class="emphasis"><em>retain-intersection</em></span> (the default) keyword to retain an intersection of all events as defined by two or more data windows. All events removed from any of the intersected data windows are entered into the remove stream. This is the default behavior if neither retain keyword is specified.
				</p>
				<p>
					Use the <span class="emphasis"><em>retain-union</em></span> keyword to retain a union of all events as defined by two or more data windows. Only events removed from all data windows are entered into the remove stream.
				</p>
				<p>
					The next example statement totals the price of OrderEvent events in a union of the last 30 seconds and unique by product name:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price) from OrderEvent#time(30 sec)#unique(productName) retain-union</pre>
				<p>
					In the above statement, all OrderEvent events that are either less then 30 seconds old or that are the last event for the product name are considered.
				</p>
				<p>
					Here is an example statement totals the price of OrderEvent events in an intersection of the last 30 seconds and unique by product name:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price) from OrderEvent#time(30 sec)#unique(productName) retain-intersection</pre>
				<p>
					In the above statement, only those OrderEvent events that are both less then 30 seconds old and are the last event for the product name are considered. The number of events that the runtime retains is the number of unique events per product name in the last 30 seconds (and not the number of events in the last 30 seconds).
				</p>
				<p>
					For an intersection the runtime retains the minimal number of events representing that intersection. Thus when combining a time window of 30 seconds and a last-event window, for example, the number of events retained at any time is zero or one event (and not 30 seconds of events).
				</p>
				<p>
					When combining a batch window into an intersection with another data window the combined data window gains batching semantics: Only when the batch criteria is fulfilled does the runtime provide the batch of intersecting insert stream events. Multiple batch data windows may not be combined into an intersection.
				</p>
				<p>
					The table below provides additional examples for data window intersections:
				</p>
				<div class="table"><a id="d0e8741"></a>
					<p class="title"><b>Table 5.3. Intersection Data Window Examples</b></p>
					<div class="table-contents">
						<table summary="Intersection Data Window Examples" border="1">
							<colgroup>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th>Example</th>
									<th>Description</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td><code class="literal">#time(30)#firstunique(keys)</code></td>
									<td>Retains 30 seconds of events unique per <code class="literal">keys</code> value (first event per value).</td>
								</tr>
								<tr>
									<td><code class="literal">#firstlength(3)#firstunique(keys)</code></td>
									<td>Retains the first 3 events that are also unique per <code class="literal">keys</code> value.</td>
								</tr>
								<tr>
									<td><code class="literal">#time_batch(N seconds)#unique(keys)</code></td>
									<td>Posts a batch every N seconds that contains the last of each unique event per <code class="literal">keys</code> value.</td>
								</tr>
								<tr>
									<td><code class="literal">#time_batch(N seconds)#firstunique(keys)</code></td>
									<td>Posts a batch every N seconds that contains the first of each unique event per <code class="literal">keys</code> value.</td>
								</tr>
								<tr>
									<td><code class="literal">#length_batch(N)#unique(keys)</code></td>
									<td>Posts a batch of unique events (last event per value) when N unique events per <code class="literal">keys</code> value are encountered.</td>
								</tr>
								<tr>
									<td><code class="literal">#length_batch(N)#firstunique(keys)</code></td>
									<td>Posts a batch of unique events (first event per value) when N unique events per <code class="literal">keys</code> value are encountered.</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-from-clause-stream-name"></a>5.4.5. Using the Stream Name</h3>
						</div>
					</div>
				</div>
				<p>
					Your <code class="literal">from</code> clause may assign a name to each stream. This assigned stream name can serve any of the following purposes.
				</p>
				<p>
					First, the stream name can be used to disambiguate property names. The <code class="literal">stream_name.property_name</code> syntax uniquely identifies which property to select if property names overlap between streams. Here is an example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select prod.productId, ord.productId from ProductEvent as prod, OrderEvent as ord</pre>
				<p>
					Second, the stream name can be used with a wildcard (*) character to select events in a join, or assign new names to the streams in a join:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Select ProductEvent only
select prod.* from ProductEvent as prod, OrderEvent</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Assign column names 'product' and 'order' to each event
select prod.* as product, ord.* as order from ProductEvent as prod, OrderEvent as ord</pre>
				<p>
					Further, the stream name by itself can occur in any expression: The runtime passes the event itself to that expression. For example, the runtime passes the ProductEvent and the OrderEvent to the user-defined function 'checkOrder':
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select prod.productId, MyFunc.checkOrder(prod, ord) 
from ProductEvent as prod, OrderEvent as ord</pre>
				<p>
					Last, you may invoke an instance method on each event of a stream, and pass parameters to the instance method as well. Instance method calls are allowed anywhere in an expression.
				</p>
				<p>
					The next statement demonstrates this capability by invoking a method 'computeTotal' on OrderEvent events and a method 'getMultiplier' on ProductEvent events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select ord.computeTotal(prod.getMultiplier()) from ProductEvent as prod, OrderEvent as ord</pre>
				<p>
					Instance methods may also be chained: Your EPL may invoke a method on the result returned by a method invocation.
				</p>
				<p>
					Assume that your product event exposes a method <code class="literal">getZone</code> which returns a zone object. Assume that the Zone class declares a method <code class="literal">checkZone</code>.
					This example statement invokes a method chain:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select prod.getZone().checkZone("zone 1") from ProductEvent as prod</pre>
				<p>
					Use the backwards apostrophe ` (aka. back tick) character to escape stream names in the <code class="literal">from</code>-clause and in <code class="literal">on-</code>trigger statements (e.g. <code class="literal">from MyEvent as `order`...</code>).
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-from-clause-fromisoptional"></a>5.4.6. The <span class="emphasis"><em>From</em></span>-Clause is Optional</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">from</code>-clause in EPL is optional and is only required for subqueries. You may compile and deploy EPL statements without a <code class="literal">from</code>-clause. For example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 1 as value</pre>
				<p>
					Such an EPL statement does not output events to listeners or subscribers. However your application may call <code class="literal">iterate</code> to iterate statement results. See <a class="xref" href="apiruntime.html#apiruntime-statement-iterators" title="16.5.4. Using Iterators">Section 16.5.4, “Using Iterators”</a>.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-where-clause"></a>5.5. Specifying Search Conditions: The <span class="emphasis"><em>Where</em></span> Clause</h2>
					</div>
				</div>
			</div><a id="d0e8891" class="indexterm"></a><a id="d0e8894" class="indexterm"></a>
			<p>
				The <code class="literal">where</code> clause is an optional clause in statements. Via the <code class="literal">where</code> clause event streams can be joined and correlated.
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="tip">
				<h2>Tip</h2>
				<p>
					For filtering events in order to remove unwanted events, use filters as part of the <code class="literal">from</code> clause as described in <a class="xref" href="epl_clauses.html#epl-from-clause-filter" title="5.4.1. Filter-Based Event Streams">Section 5.4.1, “Filter-Based Event Streams”</a>
					or for patterns in <a class="xref" href="event_patterns.html#pattern-filter" title="7.4. Filter Expressions in Patterns">Section 7.4, “Filter Expressions in Patterns”</a>.
				</p>
				<p>
					Place expressions that remove unwanted events into parenthesis right after the event type, like <code class="literal">... from OrderEvent(fraud.severity = 5 and amount &gt; 500) ...</code>.
					There is related information at <a class="xref" href="processingmodel.html#processingmodel_indexes_filterindexes" title="2.18.2. Filter Indexes">Section 2.18.2, “Filter Indexes”</a> and <a class="xref" href="performance.html#perf-tips-5" title="24.2.5. Prefer Stream-Level Filtering Over Where-Clause Filtering">Section 24.2.5, “Prefer Stream-Level Filtering Over Where-Clause Filtering”</a>.
				</p>
			</div>
			<p>
				Any expression can be placed in the <code class="literal">where</code> clause. Typically you would use comparison operators <code class="literal">=, &lt; , &gt; , &gt;=, &lt;=, !=, &lt;&gt;, is null, is not null</code> and logical combinations via <code class="literal">and</code> and <code class="literal">or</code> for joining, correlating or comparing events.
				The <code class="literal">where</code> clause introduces join conditions as outlined in <a class="xref" href="epl_clauses.html#epl-join" title="5.12. Joining Event Streams">Section 5.12, “Joining Event Streams”</a>.
			</p>
			<p>
				Some examples are listed below.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">...where settlement.orderId = order.orderId</pre>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">...where exists (select orderId from Settlement#time(1 min) where settlement.orderId = order.orderId)</pre>
			<p>
				The following two statements are equivalent since both query filter events by the <code class="literal">amount</code> property value and both statements do not specify a data window.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// preferable: specify filter criteria with the "eventtype(...filters...)" notation
@name('first') select * from Withdrawal(amount &gt; 200)</pre>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// equivalent only when there is no data window
@name('second') select * from Withdrawal where amount &gt; 200</pre>
			<p>
				You can control whether the compiler rewrites the second statement to the form of the first statement. If you specify @Hint('disable_whereexpr_moveto_filter') you can instruct the compiler to not move the <code class="literal">where</code>-clause expression into the filter.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-grouping-aggregating"></a>5.6. Aggregates and Grouping: The <span class="emphasis"><em>Group-By</em></span> Clause and the <span class="emphasis"><em>Having</em></span> Clause</h2>
					</div>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-grouping-aggregate-functions"></a>5.6.1. Using Aggregate Functions</h3>
						</div>
					</div>
				</div>
				<p>
					The aggregate functions are further documented in <a class="xref" href="functionreference.html#epl-function-aggregation" title="10.2. Aggregation Functions">Section 10.2, “Aggregation Functions”</a>.
					You can use aggregate functions to calculate and summarize data from event properties.
				</p>
				<p>
					For example, to find out the total price for all stock tick events in the last 30 seconds, type:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price) from StockTickEvent#time(30 sec)</pre>
				<p>
					Aggregation functions do not require the use of data windows. The examples herein specify data windows for the purpose of example.
					An alternative means to instruct the runtime when to start and stop aggregating and on what level to aggregate is via context declarations.
				</p>
				<p>
					For example, to find out the total price for all stock tick events since statement start, type:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price) from StockTickEvent</pre>
				<p>
					Here is the syntax for aggregate functions:
				</p>
				<pre class="synopsis"><span class="emphasis"><em>aggregate_function</em></span>( [all | distinct] <span class="emphasis"><em>expression</em></span> [,<span class="emphasis"><em>expression</em></span> [,...]] 
    [, group_by:<span class="emphasis"><em>local_group_by</em></span>] [, filter:<span class="emphasis"><em>filter_expression</em></span>] )</pre>
				<p>
					You can apply aggregate functions to all events in an event stream window or to one or more groups of events (i.e. <code class="literal">group by</code>). From each set of events to which an aggregate function is applied the runtime generates a single value.
				</p>
				<p>
					<code class="literal">Expression</code> is usually an event property name. However it can also be a constant, function, or any combination of event property names, constants,
					and functions connected by arithmetic operators.
				</p>
				<p>
					You can provide a grouping dimension for each aggregation function by providing the optional <code class="literal">group_by</code> parameter as part of aggregation function parameters.
					Please refer to <a class="xref" href="epl_clauses.html#epl-grouping-agglocal" title="5.6.4. Specifying Grouping for Each Aggregation Function">Section 5.6.4, “Specifying Grouping for Each Aggregation Function”</a>.
				</p>
				<p>
					You can provide a filter expression for each aggregation function by providing the optional <code class="literal">filter</code> parameter as part of aggregation function parameters.
					Please refer to <a class="xref" href="epl_clauses.html#epl-grouping-aggfilter" title="5.6.5. Specifying a Filter Expression for Each Aggregation Function">Section 5.6.5, “Specifying a Filter Expression for Each Aggregation Function”</a>.
				</p>
				<p>
					For example, to find out the average price for all stock tick events in the last 30 seconds if the price was doubled:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select avg(price * 2) from StockTickEvent#time(30 seconds)</pre>
				<p>
					You can use the optional keyword <code class="literal">distinct</code> with all aggregate functions to eliminate duplicate values before the aggregate function is applied. The optional
					keyword <code class="literal">all</code> which performs the operation on all events is the default.
				</p>
				<p>
					You can use aggregation functions in a <code class="literal">select</code> clause and in a <code class="literal">having</code> clause. You cannot use aggregate functions in a <code class="literal">where</code> clause, but you can use the <code class="literal">where</code> clause to restrict the events to which the aggregate is applied. The next statement computes the average and sum of the price of stock tick events for the symbol IBM only, for the last 10 stock tick events regardless of their symbol.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 'IBM stats' as title, avg(price) as avgPrice, sum(price) as sumPrice
from StockTickEvent#length(10)
where symbol='IBM'</pre>
				<p>
					In the above example the length window of 10 elements is not affected by the <code class="literal">where</code> clause, i.e. all events enter and leave the length window regardless of their symbol. If you only care about the last 10 IBM events, you need to add filter criteria as below.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 'IBM stats' as title, avg(price) as avgPrice, sum(price) as sumPrice
from StockTickEvent(symbol='IBM')#length(10)
where symbol='IBM'</pre>
				<p>
					You can use aggregate functions with any type of event property or expression, with the following exceptions:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								You can use <code class="literal">sum, avg, median, stddev, avedev</code> with numeric event properties only
							</p>
						</li>
					</ol>
				</div>
				<p>
					The runtime ignores any null values returned by the event property or expression on which the aggregate function is operating, except for the <code class="literal">count(*)</code> function, which counts null values as well. All aggregate functions return null if the data set contains no events, or if all events in the data set contain only null values for the aggregated expression.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-grouping-group-by"></a>5.6.2. Organizing Statement Results into Groups: The <span class="emphasis"><em>Group-by</em></span> Clause</h3>
						</div>
					</div>
				</div><a id="d0e9088" class="indexterm"></a><a id="d0e9091" class="indexterm"></a>
				<p>
					The <code class="literal">group by</code> clause is optional in all statements. The <code class="literal">group by</code> clause divides the output of a statement into groups. You can group by one or more event property names, or by the result of computed expressions. When used with aggregate functions, <code class="literal">group by</code> retrieves the calculations in each subgroup. You can use <code class="literal">group by</code> without aggregate functions, but generally that can produce confusing results.
				</p>
				<p>
					For example, the below statement returns the total price per symbol for all stock tick events in the last 30 seconds:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(price) from StockTickEvent#time(30 sec) group by symbol</pre>
				<p>
					The syntax of the <code class="literal">group by</code> clause is:
				</p>
				<pre class="synopsis">group by <span class="emphasis"><em>aggregate_free_expression</em></span> [, <span class="emphasis"><em>aggregate_free_expression</em></span>] [, ...]</pre>
				<p>
					The compiler places the following restrictions on expressions in the <code class="literal">group by</code> clause:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Expressions in the <code class="literal">group by</code> cannot contain aggregate functions.
							</p>
						</li>
						<li>
							<p>
								When grouping an unbound stream, i.e. no data window is specified onto the stream providing groups, or when using output rate limiting with the ALL keyword, you should ensure your group-by expression does not return an unlimited number of values. If, for example, your group-by expression is a fine-grained timestamp, group state that accumulates for an unlimited number of groups potentially reduces available memory significantly.
								Use a @Hint as described below to instruct the runtime when to discard group state.
							</p>
						</li>
					</ol>
				</div>
				<p>
					You can list more then one expression in the <code class="literal">group by</code> clause to nest groups. Once the sets are established with <code class="literal">group by</code> the aggregation
					functions are applied. Further detail on key expressions can be found at <a class="xref" href="epl_clauses.html#epl-syntax-compositekey" title="5.2.13. Composite Keys and Array Values as Keys">Section 5.2.13, “Composite Keys and Array Values as Keys”</a>.
				</p>
				<p>
					This statement posts the median volume for all stock tick events in the last 30 seconds per symbol and tick data feed. The runtime posts one event for each group to statement listeners:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, median(volume) 
from StockTickEvent#time(30 sec) 
group by symbol, tickDataFeed</pre>
				<p>
					In the statement above the event properties in the <code class="literal">select</code> list (symbol, tickDataFeed) are also listed in the <code class="literal">group by</code> clause.
					The statement thus follows the SQL standard which prescribes that non-aggregated event properties in the <code class="literal">select</code> list must match the
					<code class="literal">group by</code> columns.
				</p>
				<p>
					EPL also supports statements in which one or more event properties in the <code class="literal">select</code> list are not listed in the <code class="literal">group by</code> clause.
					The statement below demonstrates this case. It calculates the standard deviation since statement start over stock ticks aggregating by symbol and posting for
					each event the symbol, tickDataFeed and the standard deviation on price.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, stddev(price) from StockTickEvent group by symbol</pre>
				<p>
					The above example still aggregates the <code class="literal">price</code> event property based on the <code class="literal">symbol</code>, but produces one event per incoming event, not one
					event per group.
				</p>
				<p>
					Additionally, EPL supports statements in which one or more event properties in the <code class="literal">group by</code> clause are not listed in the <code class="literal">select</code> list.
					This is an example that calculates the mean deviation per <code class="literal">symbol</code> and <code class="literal">tickDataFeed</code> and posts one event per group with <code class="literal">symbol</code> and mean deviation of price in the generated events. Since tickDataFeed is not in the posted results, this can potentially be confusing.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, avedev(price) 
from StockTickEvent#time(30 sec) 
group by symbol, tickDataFeed</pre>
				<p>
					Expressions are also allowed in the <code class="literal">group by</code> list:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol * price, count(*) from StockTickEvent#time(30 sec) group by symbol * price</pre>
				<p>
					If the <code class="literal">group by</code> expression resulted in a null value, the null value becomes its own group. All null values are aggregated into the same group. If you are using the <code class="literal">count(expression)</code> aggregate function which does not count null values, the count returns zero if only null values are encountered.
				</p>
				<p>
					You can use a <code class="literal">where</code> clause in a statement with <code class="literal">group by</code>. Events that do not satisfy the conditions in the <code class="literal">where</code> clause are eliminated before any grouping is done. For example, the statement below posts the number of stock ticks in the last 30 seconds with a volume larger then 100, posting one event per group (symbol).
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, count(*) from StockTickEvent#time(30 sec) where volume &gt; 100 group by symbol</pre>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-groupby-hints"></a>5.6.2.1. Hints Pertaining to Group-By</h4>
							</div>
						</div>
					</div>
					<p>
						The runtime reclaims aggregation state agressively when it determines that a group has no data points, based on the data in the data windows. When your application data creates a large number of groups with a small or zero number of data points then performance may suffer as state is reclaimed and created anew. EPL provides the <code class="literal">@Hint('disable_reclaim_group')</code> hint that you can specify as part of a statement to avoid group reclaim.
					</p>
					<p>
						When aggregating values over an unbound stream (i.e. no data window is specified onto the stream) and when your group-by expression returns an unlimited number of values, for example when a timestamp expression is used,
						then please note the next hint.
					</p>
					<p>
						A sample statement that aggregates stock tick events by timestamp, assuming the event type offers a property by name <code class="literal">timestamp</code> that, reflects time in high resolution, for example arrival or system time:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Note the below statement could lead to an out-of-memory problem:
select symbol, sum(price) from StockTickEvent group by timestamp</pre>
					<p>
						As the runtime has no means of detecting when aggregation state (sums per symbol) can be discarded, you may use the following hints to control aggregation state lifetime.
					</p>
					<p>
						The @Hint("<code class="literal">reclaim_group_aged=</code><span class="emphasis"><em>age_in_seconds</em></span>") hint instructs the runtime to discard aggregation state that has not been
						updated for <span class="emphasis"><em>age_in_seconds</em></span> seconds.
					</p>
					<p>
						The optional @Hint("<code class="literal">reclaim_group_freq=</code><span class="emphasis"><em>sweep_frequency_in_seconds</em></span>") can be used in addition to control the frequency at which the runtime sweeps aggregation
						state to determine aggregation state age and remove state that is older then <span class="emphasis"><em>age_in_seconds</em></span> seconds.
						If the hint is not specified, the frequency defaults to the same value as <span class="emphasis"><em>age_in_seconds</em></span>.
					</p>
					<p>
						The updated sample statement with both hints:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Instruct runtime to remove state older then 10 seconds and sweep every 5 seconds
@Hint('reclaim_group_aged=10,reclaim_group_freq=5')
select symbol, sum(price) from StockTickEvent group by timestamp</pre>
					<p>
						Variables may also be used to provide values for <span class="emphasis"><em>age_in_seconds</em></span> and <span class="emphasis"><em>sweep_frequency_in_seconds</em></span>.
					</p>
					<p>
						This example statement uses a variable named <code class="literal">varAge</code> to control how long aggregation state remains in memory, and the runtime defaults the sweep frequency to the same value as the variable provides:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hint('reclaim_group_aged=varAge')
select symbol, sum(price) from StockTickEvent group by timestamp</pre>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-grouping-rollup"></a>5.6.3. Using Group-By with Rollup, Cube and Grouping Sets</h3>
						</div>
					</div>
				</div>
				<p>
					EPL supports the SQL-standard <code class="literal">rollup</code>, <code class="literal">cube</code> and <code class="literal">grouping sets</code> keywords. These keywords are available only in the <code class="literal">group-by</code> clause and instruct the runtime to compute higher-level (or super-aggregate) aggregation values, i.e. to perform multiple levels of analysis (groupings) at the same time.
				</p>
				<p>
					EPL also supports the SQL-standard <code class="literal">grouping</code> and <code class="literal">grouping_id</code> functions. These functions can be used in the <code class="literal">select</code>-clause, <code class="literal">having</code>-clause or <code class="literal">order by</code>-clause to obtain information about the current row's grouping level in expressions. Please see <a class="xref" href="functionreference.html#epl-single-row-function-grouping" title="10.1.8. The Grouping Function">Section 10.1.8, “The Grouping Function”</a>.
				</p>
				<p>
					Detailed examples and information in respect to output rate limiting can be found in <a class="xref" href="appendix_outputspec.html#outputspec-groupedrowpergrouprollup" title="A.7. Output for Fully-Aggregated, Grouped Statements With Rollup">Section A.7, “Output for Fully-Aggregated, Grouped Statements With Rollup”</a>.
				</p>
				<p>
					Use the <code class="literal">rollup</code> keyword in the <code class="literal">group-by</code> lists of expressions to compute the equivalent of an OLAP dimension or hierarchy.
				</p>
				<p>
					For example, the following statement outputs for each incoming event three rows. The first row contains the total volume per symbol and feed, the second row contains the total volume per symbol and the third row contains the total volume overall. This example aggregates across all events for each aggregation level (3 groupings) since it declares no data window:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, sum(volume) from StockTickEvent
group by rollup(symbol, tickDataFeed)</pre>
				<p>
					The value of <code class="literal">tickDataFeed</code> is <code class="literal">null</code> for the output row that contains the total per symbol and the output row that contains the total volume overall.
					The value of both <code class="literal">symbol</code> and <code class="literal">tickDataFeed</code> is <code class="literal">null</code> for the output row that contains the overall total.
				</p>
				<p>
					Use the <code class="literal">cube</code> keyword in the <code class="literal">group-by</code> lists of expressions to compute a cross-tabulation.
				</p>
				<p>
					The following statement outputs for each incoming event four rows. The first row contains the total volume per symbol and feed, the second row contains the total volume per symbol, the third row contains the total volume per feed and the forth row contains the total volume overall (4 groupings):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, sum(volume) from StockTickEvent
group by cube(symbol, tickDataFeed)</pre>
				<p>
					The <code class="literal">grouping sets</code> keywords allows you to specify only the groupings you want. It can thus be used to generate the same groupings that simple <code class="literal">group-by</code> expressions, <code class="literal">rollup</code> or <code class="literal">cube</code> would produce.
				</p>
				<p>
					In this example each incoming event causes the runtime to compute two output rows: The first row contains the total volume per symbol and the second row contains the total volume per feed (2 groupings):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, sum(volume) from StockTickEvent
group by grouping sets(symbol, feed)</pre>
				<p>
					Your <code class="literal">group-by</code> expression can list grouping expressions and use <code class="literal">rollup</code>, <code class="literal">cube</code> and <code class="literal">grouping sets</code> keywords in addition or in combination.
				</p>
				<p>
					This statement outputs the total per combination of symbol and feed and the total per symbol (2 groupings):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, sum(volume) from StockTickEvent
group by symbol, rollup(tickDataFeed)</pre>
				<p>
					You can specify combinations of expressions by using parenthesis.
				</p>
				<p>
					The next statement is equivalent and also outputs the total per symbol and feed and the total per symbol (2 groupings, note the parenthesis):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, sum(volume) from StockTickEvent
group by grouping sets ((symbol, tickDataFeed), symbol)</pre>
				<p>
					Use empty parenthesis to aggregate across all dimensions.
				</p>
				<p>
					This statement outputs the total per symbol, the total per feed and the total overall (3 groupings):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, sum(volume) from StockTickEvent
group by grouping sets (symbol, tickDataFeed, ())</pre>
				<p>
					The order of any output events for both insert and remove stream data is well-defined and exactly as indicated before. For example, specifying <code class="literal">grouping sets ((), symbol, tickDataFeed)</code> outputs a total overall, a total by symbol and a total by feed in that order. If the statement has an <code class="literal">order-by</code>-clause then the ordering criteria of the <code class="literal">order-by</code>-clause take precedence.
				</p>
				<p>
					You can use <code class="literal">rollup</code> and <code class="literal">cube</code> within <code class="literal">grouping sets</code>.
				</p>
				<p>
					This statement outputs the total per symbol and feed, the total per symbol, the total overall and the total by feed (4 groupings):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, tickDataFeed, sum(volume) from StockTickEvent
group by grouping sets (rollup(symbol, tickDataFeed), tickDataFeed)</pre>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						In order to use any of the <code class="literal">rollup</code>, <code class="literal">cube</code> and <code class="literal">grouping sets</code> keywords the statement must be fully-aggregated.
						All non-aggregated properties in the <code class="literal">select</code>-clause, <code class="literal">having</code>-clause or <code class="literal">order-by</code>-clause must also be listed in the <code class="literal">group by</code> clause.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-grouping-rollup-examples"></a>5.6.3.1. Grouping Dimension Examples</h4>
							</div>
						</div>
					</div>
					<p>
						This section provides additional examples of <code class="literal">group-by</code>-clauses and groupings or dimensions.
						The examples use event properties <code class="literal">a, b, c, d, e</code> to keep the examples easy to read.
						Empty parenthesis <code class="literal">()</code> stand for aggregation overall (across all dimensions).
					</p>
					<p>
						If a statement provides no <code class="literal">order-by</code> clause, its order of output events is exactly as indicated below. Otherwise <code class="literal">order-by</code> takes precedence
						and within the same ordering criteria the order of output events is as indicated below.
					</p>
					<div class="table"><a id="d0e9497"></a>
						<p class="title"><b>Table 5.4. </b></p>
						<div class="table-contents">
							<table summary="" border="1">
								<colgroup>
									<col>
									<col>
								</colgroup>
								<thead>
									<tr>
										<th><code class="literal">Group-By</code> Clause</th>
										<th>Grouping</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">group by a, b, c</pre>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">a, b, c</pre>
										</td>
									</tr>
									<tr>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">group by rollup(a, b, c)</pre>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">a, b, c
a, b
a
()</pre>
										</td>
									</tr>
									<tr>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">group by a, rollup(b, c)</pre>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">a, b, c
a, b
a</pre>
										</td>
									</tr>
									<tr>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">group by rollup(a, b), rollup(c, d)</pre>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">a,b,c,d
a,b,c
a,b
a,c,d
a,c
a
c,d
c
()</pre>
										</td>
									</tr>
									<tr>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">group by cube(a, b, c)</pre>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">a, b, c
a, b
a, c
a
b, c
b
c
()</pre>
										</td>
									</tr>
									<tr>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">group by cube(a, b, c, d)</pre>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">a,b,c,d
a,b,c
a,b,d
a,b
a,c,d
a,c
a,d
a
b,c,d
b,c
b,d
b
c,d
c
d
()</pre>
										</td>
									</tr>
									<tr>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">group by grouping sets(a, b, c)</pre>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">a
b
c</pre>
										</td>
									</tr>
									<tr>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">group by grouping sets((a, b), rollup(c, d))</pre>
										</td>
										<td>
											<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">a,b
c,d
c
()</pre>
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div><br class="table-break">
					<p>
						The following table outlines sample equivalent <code class="literal">group-by</code>-clauses.
					</p>
					<div class="table"><a id="d0e9572"></a>
						<p class="title"><b>Table 5.5. Equivalent <code class="literal">Group-By</code>-Clause Expressions</b></p>
						<div class="table-contents">
							<table summary="Equivalent Group-By-Clause Expressions" border="1">
								<colgroup>
									<col>
									<col>
								</colgroup>
								<thead>
									<tr>
										<th>Expression</th>
										<th>Equivalent</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td>group by a, b</td>
										<td>group by grouping sets((a, b))</td>
									</tr>
									<tr>
										<td>group by rollup(a, b)</td>
										<td>group by grouping sets((a, b), a, ())</td>
									</tr>
									<tr>
										<td>group by cube(a, b)</td>
										<td>group by grouping sets((a, b), a, b, ())</td>
									</tr>
									<tr>
										<td>group by a, b, rollup(c, d)</td>
										<td>group by grouping sets((a, b, c, d), (a, b, c), (a, b))</td>
									</tr>
									<tr>
										<td>group by rollup((a, b), c)</td>
										<td>group by grouping sets((a, b, c), (a, b), ())</td>
									</tr>
									<tr>
										<td>group by grouping sets((a))</td>
										<td>group by grouping sets(a)</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div><br class="table-break">
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-grouping-rollup-other"></a>5.6.3.2. Rollup Usage Notes</h4>
							</div>
						</div>
					</div>
					<p>
						The <code class="literal">prev</code> and <code class="literal">prior</code> functions returns the previous event's property values and since they are not aggregation functions
						return the same value for each grouping. Declared or alias expressions and correlated subqueries also receive the same value for each grouping.
					</p>
					<p>
						Context partitions operate on a higher level then rollups, i.e. rollups are never across context partitions.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-grouping-agglocal"></a>5.6.4. Specifying Grouping for Each Aggregation Function</h3>
						</div>
					</div>
				</div>
				<p>
					EPL allows each aggregation function to specify its own grouping criteria. This is useful for aggregating across multiple dimensions.
				</p>
				<p>
					The syntax for the <code class="literal">group_by</code> parameter for use with aggregation functions is:
				</p>
				<pre class="synopsis">group_by: ( [<span class="emphasis"><em>expression</em></span> [,<span class="emphasis"><em>expression</em></span> [,...]]] )</pre>
				<p>
					The <code class="literal">group_by</code> identifier can occur at any place within the aggregation function parameters. It follows a colon and within parenthesis an
					optional list of grouping expressions. The parenthesis are not required when providing a single expression.
					For grouping on the top level (overall aggregation) please use <code class="literal">()</code> empty parenthesis.
					Further detail on key expressions can be found at <a class="xref" href="epl_clauses.html#epl-syntax-compositekey" title="5.2.13. Composite Keys and Array Values as Keys">Section 5.2.13, “Composite Keys and Array Values as Keys”</a>.
				</p>
				<p>
					The presence of <code class="literal">group_by</code> aggregation function parameters, the grouping expressions as well as the <code class="literal">group-by</code> clause
					determine the number of output rows for statements as further described in <a class="xref" href="processingmodel.html#processingmodel_aggregation" title="2.15. Basic Aggregated Statement Types">Section 2.15, “Basic Aggregated Statement Types”</a>.
				</p>
				<p>
					For un-grouped statements (without a <code class="literal">group by </code> clause), if any aggregation function specifies a <code class="literal">group_by</code> other than the <code class="literal">()</code> overall group, the statement executes
					as aggregated and un-grouped.
				</p>
				<p>
					For example, the next statement is an aggregated (but not fully aggregated) and ungrouped statement and outputs various totals for each arriving event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price, group_by:()) as totalPriceOverall,
  sum(price, group_by:account) as totalPricePerAccount,
  sum(price, group_by:(account, feed)) as totalPricePerAccountAndFeed
from Orders</pre>
				<p>
					For grouped statements (with a <code class="literal">group by </code> clause), if all aggregation functions specifiy either no <code class="literal">group_by</code> or <code class="literal">group_by</code> criteria that subsume the criteria in the <code class="literal">group by</code> clause, the statement executes as a fully-aggregated and grouped statement. Otherwise the statement executes as an aggregated and grouped statement.
				</p>
				<p>
					The next example is fully-aggregated and grouped and it computes, for the last one minute of orders, the ratio of orders per account compared to all orders:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*)/count(*, group_by:()) as ratio
from Orders#time(1 min) group by account</pre>
				<p>
					The next example is an aggregated (and not fully-aggregated) and grouped statement that in addition outputs a count per order category:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*) as cnt, count(*, group_by:()) as cntOverall,  count(*, group_by:(category))  as cntPerCategory
from Orders#time(1 min) group by account</pre>
				<p>
					Please note the following restrictions:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Expressions in the <code class="literal">group_by</code> cannot contain aggregate functions.
							</p>
						</li>
						<li>
							<p>
								Hints pertaining to group-by are not available when a statement specifies aggregation functions with <code class="literal">group_by</code>.
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">group_by</code> aggregation function parameters are not available in subqueries, match-recognize, statements that aggregate into tables using <code class="literal">into table</code> or in combination with <code class="literal">rollup</code> and <code class="literal">grouping sets</code>.
							</p>
						</li>
					</ol>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-grouping-aggfilter"></a>5.6.5. Specifying a Filter Expression for Each Aggregation Function</h3>
						</div>
					</div>
				</div>
				<p>
					EPL allows each aggregation function to specify its own filter expression. This is useful for conditionally aggregating.
				</p>
				<p>
					The syntax for the <code class="literal">filter</code> parameter for use with aggregation functions is:
				</p>
				<pre class="synopsis">filter:<span class="emphasis"><em>expression</em></span></pre>
				<p>
					The <code class="literal">filter</code> identifier can occur at any place within the aggregation function parameters. It follows a colon and the filter expression.
					The filter expression must return a <code class="literal">boolean</code>-type value.
				</p>
				<p>
					If a filter expression is present, the runtime evaluates the filter expression to determine whether to update the aggregation.
				</p>
				<p>
					For example, the next statement returns the total price of small orders (price less 100), the total price of large orders (price &gt;= 100), as well as the events themselves of each category, considering the last 10 seconds of orders:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 
  sum(price, filter: price &lt; 100) as smallOrderTotal, 
  sum(price, filter: price &gt;= 100) as largeOrderTotal, 
  window(*, filter: price &lt; 100) as smallOrderEvents, 
  window(*, filter: price &gt;= 100) as largeOrderEvents
    from Orders#time(10)</pre>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						Filter expression that are parameters to aggregation functions must return reproducible results:
						When the expression is evaluated against the same input values it should return the same result.
						Aggregation functions and subqueries are not allowed therein.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-grouping-having"></a>5.6.6. Selecting Groups of Events: The <span class="emphasis"><em>Having</em></span> Clause</h3>
						</div>
					</div>
				</div><a id="d0e9773" class="indexterm"></a><a id="d0e9776" class="indexterm"></a>
				<p>
					Use the <code class="literal">having</code> clause to pass or reject events defined by the <code class="literal">group-by</code> clause. The <code class="literal">having</code> clause sets conditions for the <code class="literal">group by</code> clause in the same way <code class="literal">where</code> sets conditions for the <code class="literal">select</code> clause, except <code class="literal">where</code> cannot include aggregate functions, while <code class="literal">having</code> often does.
				</p>
				<p>
					This statement is an example of a <code class="literal">having</code> clause with an aggregate function. It posts the total price per symbol for the last 30 seconds of stock tick events for only those symbols in which the total price exceeds 1000. The <code class="literal">having</code> clause eliminates all symbols where the total price is equal or less then 1000.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(price) 
from StockTickEvent#time(30 sec) 
group by symbol 
having sum(price) &gt; 1000</pre>
				<p>
					To include more then one condition in the <code class="literal">having</code> clause combine the conditions with <code class="literal">and</code>, <code class="literal">or</code> or <code class="literal">not</code>.
					This is shown in the statement below which selects only groups with a total price greater then 1000 and an average volume less then 500.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(price), avg(volume)
from StockTickEvent#time(30 sec) 
group by symbol 
having sum(price) &gt; 1000 and avg(volume) &lt; 500</pre>
				<p>
					A statement with the <code class="literal">having</code> clause should also have a <code class="literal">group by</code> clause. If you omit <code class="literal">group-by</code>, all the events not excluded
					by the <code class="literal">where</code> clause return as a single group. In that case <code class="literal">having</code> acts like a <code class="literal">where</code> except that <code class="literal">having</code> can have aggregate functions.
				</p>
				<p>
					The <code class="literal">having</code> clause can also be used without <code class="literal">group by</code> clause as the below example shows. The example below posts events where the price is less then the current running average price of all stock tick events in the last 30 seconds.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, price, avg(price) 
from StockTickEvent#time(30 sec) 
having price &lt; avg(price)</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-filter-where-grouping-having-interactions"></a>5.6.7. How the Stream Filter, <span class="emphasis"><em>Where</em></span>, <span class="emphasis"><em>Group By</em></span> and <span class="emphasis"><em>Having</em></span>-Clauses Interact</h3>
						</div>
					</div>
				</div>
				<p>
					When you include filters, the <code class="literal">where</code> condition, the <code class="literal">group by</code> clause and the <code class="literal">having</code> condition in a statement
					the sequence in which each clause affects events determines the final result:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								The event stream's filter condition, if present, dictates which events enter a window (if one is used). The filter discards any events not meeting filter criteria.
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">where</code> clause excludes events that do not meet its search condition.
							</p>
						</li>
						<li>
							<p>
								Aggregate functions in the select list calculate summary values for each group.
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">having</code> clause excludes events from the final results that do not meet its search condition.
							</p>
						</li>
					</ol>
				</div>
				<p>
					The following statement illustrates the use of filter, <code class="literal">where</code>, <code class="literal">group by</code> and <code class="literal">having</code> clauses in one statement with
					a <code class="literal">select</code> clause containing an aggregate function.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select tickDataFeed, stddev(price)
from StockTickEvent(symbol='IBM')#length(10) 
where volume &gt; 1000
group by tickDataFeed 
having stddev(price) &gt; 0.8</pre>
				<p>
					The runtime filters events using the filter criteria for the event stream <code class="literal">StockTickEvent</code>. In the example above only events with symbol IBM enter the length window over the last 10 events, all other events are simply discarded. The <code class="literal">where</code> clause removes any events posted by the length window (events entering the window and event leaving the window) that do not match the condition of volume greater then 1000. Remaining events are applied to the <code class="literal">stddev</code> standard deviation aggregate function for each tick data feed as specified in the <code class="literal">group by</code> clause. Each <code class="literal">tickDataFeed</code> value generates one event. The runtime applies the <code class="literal">having</code> clause and only lets events pass for <code class="literal">tickDataFeed</code> groups with a standard deviation of price greater then 0.8.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-group-by-versus-view"></a>5.6.8. Comparing Keyed Segmented Context, the <span class="emphasis"><em>Group By</em></span> Clause and <span class="emphasis"><em>#groupwin</em></span> for Data Windows</h3>
						</div>
					</div>
				</div>
				<p>
					The keyed segmented context <span class="emphasis"><em>create context ... partition by</em></span> and the <span class="emphasis"><em>group by</em></span> clause as well as the built-in <span class="emphasis"><em>#groupwin</em></span> are similar in their ability to group events but very different in their semantics. This section explains the key differences in their behavior and use.
				</p>
				<p>
					The keyed segmented context as declared with <span class="emphasis"><em>create context ... partition by</em></span> and <span class="emphasis"><em>context .... select ...</em></span> creates a new context partition per key value(s). The runtime maintains separate data windows as well as separate aggregations per context partition; thereby the keyed segmented context applies to both. See <a class="xref" href="context.html#context_def_keyed" title="4.2.2. Keyed Segmented Context">Section 4.2.2, “Keyed Segmented Context”</a> for additional examples.
				</p>
				<p>
					The <span class="emphasis"><em>group by</em></span> clause works together with aggregation functions in your statement to produce an aggregation result per group. In greater detail, this means that when a new event arrives, the runtime applies the expressions in the <span class="emphasis"><em>group by</em></span> clause to determine a grouping key. If the runtime has not encountered that grouping key before (a new group), the runtime creates a set of new aggregation results for that grouping key and performs the aggregation changing that new set of aggregation results. If the grouping key points to an existing set of prior aggregation results (an existing group), the runtime performs the aggregation changing the prior set of aggregation results for that group.
				</p>
				<p>
					The <span class="emphasis"><em>#groupwin</em></span> instructs the system to have a separate data window per group, see <a class="xref" href="epl-views.html#view-std-groupwin" title="14.3.15. Grouped Data Window (groupwin or std:groupwin)">Section 14.3.15, “Grouped Data Window (groupwin or std:groupwin)”</a>. It causes allocation of separate data window(s) for each grouping key encountered.
				</p>
				<p>
					The table below summarizes the point:
				</p>
				<div class="table"><a id="d0e9994"></a>
					<p class="title"><b>Table 5.6. Grouping Options</b></p>
					<div class="table-contents">
						<table summary="Grouping Options" border="1">
							<colgroup>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th>Option</th>
									<th>Description</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>Keyed Segmented Context</td>
									<td>
										<p>
											Separate context partition per key value.
										</p>
										<p>
											Affects all of data windows, aggregations, patterns, etc. (except variables which are global).
										</p>
									</td>
								</tr>
								<tr>
									<td>Grouped Data Window (<span class="emphasis"><em>#groupwin</em></span>)</td>
									<td>
										<p>
											Separate data window per key value.
										</p>
										<p>
											Affects only the data window that is declared next to it.
										</p>
									</td>
								</tr>
								<tr>
									<td>Group By Clause (<span class="emphasis"><em>group by</em></span>)</td>
									<td>
										<p>
											Separate aggregation values per key value.
										</p>
										<p>
											Affects only aggregation values.
										</p>
									</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
				<p>
					Please review the performance section for advice related to performance or memory-use.
				</p>
				<p>
					The next example shows statements that produce equivalent results. The statement using the <span class="emphasis"><em>group by</em></span> clause is generally preferable as is easier to read. The second form introduces the <code class="literal">#uni</code> special data window which computes univariate statistics for a given property:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, avg(price) from StockTickEvent group by symbol
// ... is equivalent to ...
select symbol, average from StockTickEvent#groupwin(symbol)#uni(price)</pre>
				<p>
					The next example shows two statements that are NOT equivalent as the length window is ungrouped in the first statement, and grouped in the second statement:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(price) from StockTickEvent#length(10) group by symbol
// ... NOT equivalent to ...
select symbol, sum(price) from StockTickEvent#groupwin(symbol)#length(10)</pre>
				<p>
					The key difference between the two statements is that in the first statement the length window is ungrouped and applies to all events regardless of group. While in the second statement each group gets its own length window. For example, in the second statement events arriving for symbol "ABC" get a length window of 10 events, and events arriving for symbol "DEF" get their own length window of 10 events.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-output-rate"></a>5.7. Stabilizing and Controlling Output: The <span class="emphasis"><em>Output</em></span> Clause</h2>
					</div>
				</div>
			</div><a id="d0e10070" class="indexterm"></a><a id="d0e10073" class="indexterm"></a>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-output-options"></a>5.7.1. Output Clause Options</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">output</code> clause is optional in EPL and is used to control or stabilize the rate at which events are output and to suppress output events. The EPL language provides for several different ways to control output rate.
				</p>
				<p>
					Here is the syntax for the <code class="literal">output</code> clause that specifies a rate in time interval or number of events:
				</p>
				<pre class="synopsis">output [after <span class="emphasis"><em>suppression_def</em></span>] 
  [[all | first | last | snapshot] every <span class="emphasis"><em>output_rate</em></span> [seconds | events]]
[and when terminated]</pre>
				<p>
					An alternate syntax specifies the time period between output as outlined in <a class="xref" href="epl_clauses.html#epl-syntax-time-periods" title="5.2.1. Specifying Time Periods">Section 5.2.1, “Specifying Time Periods”</a> :
				</p>
				<pre class="synopsis">output [after <span class="emphasis"><em>suppression_def</em></span>] 
  [[all | first | last | snapshot] every <span class="emphasis"><em>time_period</em></span>]
[and when terminated]</pre>
				<p>
					A crontab-like schedule can also be specified. The schedule parameters follow the pattern observer parameters and are further described in <a class="xref" href="event_patterns.html#pattern-timer-at" title="7.6.4. Crontab (timer:at)">Section 7.6.4, “Crontab (timer:at)”</a> :
				</p>
				<pre class="synopsis">output [after <span class="emphasis"><em>suppression_def</em></span>] 
  [[all | first | last | snapshot] at 
   (<span class="emphasis"><em>minutes, hours, days of month, months, days of week [, seconds]</em></span>)]
[and when terminated]</pre>
				<p>
					For use with contexts, in order to trigger output only when a context partition terminates, specify <code class="literal">when terminated</code> as further described in <a class="xref" href="context.html#context_outputterminated" title="4.6. Output When a Context Partition Ends (Non-Overlapping Context) or Terminates (Overlapping Context)">Section 4.6, “Output When a Context Partition Ends (Non-Overlapping Context) or Terminates (Overlapping Context)”</a>:
				</p>
				<pre class="synopsis">output [after <span class="emphasis"><em>suppression_def</em></span>] 
  [[all | first | last | snapshot] when terminated 
  [and <span class="emphasis"><em>termination_expression</em></span>]
  [then set variable_name = assign_expression [, variable_name = assign_expression [,...]]]
  ]</pre>
				<p>
					Last, output can be controlled by an expression that may contain variables, user-defined functions and information about the number of collected events. Output that is controlled by an expression is discussed in detail below.
				</p>
				<p>
					The <code class="literal">after</code> keyword and <span class="emphasis"><em>suppression_def</em></span> can appear alone or together with further output conditions and suppresses output events.
				</p>
				<p>
					For example, the following statement outputs, every 60 seconds, the total price for all orders in the 30-minute time window:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price) from OrderEvent#time(30 min) output snapshot every 60 seconds</pre>
				<p>
					The <code class="literal">all</code> keyword is the default and specifies that all events in a batch should be output, each incoming row in the batch producing an output row.
					Note that for statements that group via the <code class="literal">group by</code> clause, the <code class="literal">all</code> keyword provides special behavior as below.
				</p>
				<p>
					The <code class="literal">first</code> keyword specifies that only the first event in an output batch is to be output.
					Using the <code class="literal">first</code> keyword instructs the runtime to output the first matching event as soon as it arrives, and then ignores matching events for the time interval or number of events specified.
					After the time interval elapsed, or the number of matching events has been reached, the next first matching event is output again and the following interval the runtime again ignores matching events.
					For statements that group via the <code class="literal">group by</code> clause, the <code class="literal">first</code> keywords provides special behavior as below.
				</p>
				<p>
					The <code class="literal">last</code> keyword specifies to only output the last event at the end of the given time interval or after the given number of matching events
					have been accumulated. Again, for statements that group via the <code class="literal">group by</code> clause the <code class="literal">last</code> keyword provides special behavior as below.
				</p>
				<p>
					The <code class="literal">snapshot</code> keyword is often used with unbound streams and/or aggregation to output current aggregation results. While the other keywords control how a batch of events between output intervals is being considered, the <code class="literal">snapshot</code> keyword outputs current state of a statement independent of the last batch. Its output is comparable to the <code class="literal">iterator</code> method provided by a statement. More information on <code class="literal">output snapshot</code> can be found in <a class="xref" href="epl_clauses.html#epl-output-snapshot" title="5.7.1.3. Output Snapshot">Section 5.7.1.3, “Output Snapshot”</a>.
				</p>
				<p>
					The <span class="emphasis"><em>output_rate</em></span> is the frequency at which the runtime outputs events. It can be specified in terms of time or number of events. The value can be a number to denote a fixed output rate, or the name of a variable whose value is the output rate. By means of a variable the output rate can be controlled externally and changed dynamically at runtime.
				</p>
				<p>
					Please consult the <a class="xref" href="appendix_outputspec.html" title="Appendix A. Output Reference and Samples">Appendix A, <i>Output Reference and Samples</i></a> for detailed information on insert and remove stream output for the various <code class="literal">output</code> clause keywords.
				</p>
				<p>
					For use with contexts you may append the keywords <code class="literal">and when terminated</code> to trigger output at the rate defined and in addition trigger output when the context partition terminates. Please see <a class="xref" href="context.html#context_outputterminated" title="4.6. Output When a Context Partition Ends (Non-Overlapping Context) or Terminates (Overlapping Context)">Section 4.6, “Output When a Context Partition Ends (Non-Overlapping Context) or Terminates (Overlapping Context)”</a> for details.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						Please see <a class="xref" href="appendix_outputlimit.html" title="Appendix B. Runtime Considerations for Output Rate Limiting">Appendix B, <i>Runtime Considerations for Output Rate Limiting</i></a> for information on how the system retains input events and computes output events according to the specified output rate.
					</p>
				</div>
				<p>
					The time interval can also be specified in terms of minutes; the following statement is identical to the first one.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from StockTickEvent output every 1.5 minutes</pre>
				<p>
					A second way that output can be stabilized is by batching events until a certain number of events have been collected:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from StockTickEvent output every 5 events</pre>
				<p>
					Additionally, event output can be further modified by the optional <code class="literal">last</code> keyword, which causes output of only the last event to arrive into an output batch.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from StockTickEvent output last every 5 events</pre>
				<p>
					Using the <code class="literal">first</code> keyword you can be notified at the start of the interval. The allows to watch for situations such as a rate falling below a threshold
					and only be informed every now and again after the specified output interval, but be informed the moment it first happens.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickRate where rate&lt;100 output first every 60 seconds</pre>
				<p>
					A sample statement using the Unix "crontab"-command schedule is shown next. See <a class="xref" href="event_patterns.html#pattern-timer-at" title="7.6.4. Crontab (timer:at)">Section 7.6.4, “Crontab (timer:at)”</a> for details on schedule syntax. Here, output occurs every 15 minutes from 8am to 5:45pm (hours 8 to 17 at 0, 15, 30 and 45 minutes past the hour):
				</p>
				<pre class="synopsis">select symbol, sum(price) from StockTickEvent group by symbol output at (*/15, 8:17, *, *, *)</pre>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-output-expression"></a>5.7.1.1. Controlling Output Using an Expression</h4>
							</div>
						</div>
					</div><a id="d0e10259" class="indexterm"></a>
					<p>
						Output can also be controlled by an expression that may check variable values, use user-defined functions and statement built-in properties that provide additional information. The synopsis is as follows:
					</p>
					<pre class="synopsis">output [after <span class="emphasis"><em>suppression_def</em></span>] 
  [[all | first | last | snapshot] when <span class="emphasis"><em>trigger_expression</em></span> 
    [then set <span class="emphasis"><em>variable_name</em></span> = <span class="emphasis"><em>assign_expression</em></span> [, <span class="emphasis"><em>variable_name</em></span> = <span class="emphasis"><em>assign_expression</em></span> [,...]]]
  [and when terminated 
    [and <span class="emphasis"><em>termination_expression</em></span>]
    [then set variable_name = assign_expression [, variable_name = assign_expression [,...]]]
  ]</pre>
					<p>
						The <code class="literal">when</code> keyword must be followed by a trigger expression returning a boolean value of true or false, indicating whether to output.
						Use the optional <code class="literal">then</code> keyword to change variable values after the trigger expression evaluates to true. An assignment expression assigns a new value to variable(s).
					</p>
					<p>
						For use with contexts you may append the keywords <code class="literal">and when terminated</code> to also trigger output when the context partition terminates. Please see <a class="xref" href="context.html#context_outputterminated" title="4.6. Output When a Context Partition Ends (Non-Overlapping Context) or Terminates (Overlapping Context)">Section 4.6, “Output When a Context Partition Ends (Non-Overlapping Context) or Terminates (Overlapping Context)”</a> for details. You may optionally specify a termination expression. If that expression is provided the
						runtime evaluates the expression when the context partition terminates: The evaluation result of <code class="literal">true</code> means output occurs when the context partition terminates, <code class="literal">false</code> means no output occurs when the context partition terminates.
						You may specify <code class="literal">then set</code> followed by a list of assignments to assign variables. Assignments are executed on context partition termination regardless of the termination expression, if present.
					</p>
					<p>
						Lets consider an example. The next statement assumes that your application has defined a variable by name OutputTriggerVar of boolean type. The statement outputs rows only when the OutputTriggerVar variable has a boolean value of true:
					</p>
					<pre class="synopsis">select sum(price) from StockTickEvent output when OutputTriggerVar = true</pre>
					<p>
						The runtime evaluates the trigger expression when streams and data windows (if any) post one or more insert or remove stream events after considering the <code class="literal">where</code> clause, if present. It also evaluates the trigger expression when any of the variables used in the trigger expression, if any, changes value. Thus output occurs as follows:
					</p>
					<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
						<ol>
							<li>
								<p>
									When there are insert or remove stream events and the <code class="literal">when</code> trigger expression evaluates to true, the runtime outputs the resulting rows.
								</p>
							</li>
							<li>
								<p>
									When any of the variables in the <code class="literal">when</code> trigger expression changes value, the runtime evaluates the expression and outputs results. Result output occurs within the minimum time interval of timer resolution.
								</p>
							</li>
						</ol>
					</div>
					<p>
						By adding a <code class="literal">then</code> part to the EPL, you can reset any variables after the trigger expression evaluated to true:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price) from StockTickEvent 
  output when OutputTriggerVar = true  
  then set OutputTriggerVar = false</pre>
					<p>
						Expressions in the <code class="literal">when</code> and <code class="literal">then</code> may, for example, use variables, user defined functions or any of the built-in named properties that are described in the below list.
					</p>
					<p>
						The following built-in properties are available for use:
					</p>
					<div class="table"><a id="epl-output-expression-builtin"></a>
						<p class="title"><b>Table 5.7. Built-In Properties for Use With Output When</b></p>
						<div class="table-contents">
							<table summary="Built-In Properties for Use With Output When" border="1">
								<colgroup>
									<col>
									<col>
								</colgroup>
								<thead>
									<tr>
										<th>Built-In Property Name</th>
										<th>Description</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td><code class="literal">last_output_timestamp</code></td>
										<td>Timestamp when the last output occurred for the statement; Initially set to time of statement deployment</td>
									</tr>
									<tr>
										<td><code class="literal">count_insert</code></td>
										<td>Number of insert stream events</td>
									</tr>
									<tr>
										<td><code class="literal">count_insert_total</code></td>
										<td>Number of insert stream events in total (not reset when output occurs).</td>
									</tr>
									<tr>
										<td><code class="literal">count_remove</code></td>
										<td>Number of remove stream events</td>
									</tr>
									<tr>
										<td><code class="literal">count_remove_total</code></td>
										<td>Number of remove stream events in total (not reset when output occurs).</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div><br class="table-break">
					<p>
						The values provided by <code class="literal">count_insert</code> and <code class="literal">count_remove</code> are non-continues: The number returned for these properties may 'jump' up rather then count up by 1.
						The counts reset to zero upon output.
					</p>
					<p>
						The following restrictions apply to expressions used in the output rate clause:
					</p>
					<div class="itemizedlist">
						<ul compact="compact">
							<li>
								<p>
									Event property names cannot be used in the output clause.
								</p>
							</li>
							<li>
								<p>
									Aggregation functions cannot be used in the output clause.
								</p>
							</li>
							<li>
								<p>
									The <code class="literal">prev</code> previous event function and the <code class="literal">prior</code> prior event function cannot be used in the output clause.
								</p>
							</li>
						</ul>
					</div>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-output-suppress"></a>5.7.1.2. Suppressing Output With <code class="literal">After</code></h4>
							</div>
						</div>
					</div><a id="d0e10424" class="indexterm"></a><a id="d0e10429" class="indexterm"></a>
					<p>
						The <code class="literal">after</code> keyword and its time period or number of events parameters is optional and can occur after the <code class="literal">output</code> keyword, either alone or with output conditions as listed above.
					</p>
					<p>
						The synopsis of <code class="literal">after</code> is as follows:
					</p>
					<pre class="synopsis">output after <span class="emphasis"><em>time_period</em></span> | <span class="emphasis"><em>number</em></span> events [...]</pre>
					<p>
						When using <code class="literal">after</code> either alone or together with further output conditions, the runtime discards all output events until the time period passed as measured from the start of the statement, or until the
						number of output events are reached. The discarded events are not output and do not count towards any further output conditions if any are specified.
					</p>
					<p>
						For example, the following statement outputs every minute the total price for all orders in the 30-minute time window but only after 30 minutes have passed:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price) from OrderEvent#time(30 min) output after 30 min snapshot every 1 min</pre>
					<p>
						An example in which <code class="literal">after</code> occur alone is below, in a statement that outputs total price for all orders in the last minute but only after 1 minute passed, each time an event arrives or leaves the data window:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select sum(price) from OrderEvent#time(1 min) output after 1 min</pre>
					<p>
						To demonstrate <code class="literal">after</code> when used with an event count, this statement find pairs of orders with the same id but suppresses output for the first 5 pairs:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from pattern[every o=OrderEvent-&gt;p=OrderEvent(id=o.id)] output after 5 events</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="epl-output-snapshot"></a>5.7.1.3. Output Snapshot</h4>
							</div>
						</div>
					</div><a id="d0e10479" class="indexterm"></a>
					<p>
						For fully aggregated and un-grouped statements, <code class="literal">output snapshot</code> outputs a single row with current aggregation value(s).
					</p>
					<p>
						For aggregated ungrouped and grouped statements, as well as for unaggregated statements,
						<code class="literal">output snapshot</code> considers events held by the data window and outputs a row for each event.
						If the statement specifies no data window or a join results in no rows, the output is no rows.
					</p>
					<p>
						For fully aggregated and grouped statements that select from a single stream (or pattern, non-joining) and that do not specify a data window,
						the runtime outputs current aggregation results for all groups. For fully aggregated and grouped statements with a join and/or data windows the output consists of aggregation values
						according to events held in the data window (single stream) or that are join results (join).
					</p>
					<p>
						When the <code class="literal">from</code>-clause lists only tables, use <code class="literal">output snapshot</code> to output table contents.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-output-groupby"></a>5.7.2. Aggregation, Group By, Having and Output Clause Interaction</h3>
						</div>
					</div>
				</div>
				<p>
					Remove stream events can also be useful in conjunction with aggregation and the <code class="literal">output</code> clause: When the runtime posts remove stream events for fully-aggregated statements, it presents the aggregation state before the expiring event leaves the data window. Your application can thus easily obtain a delta between the new aggregation value and the prior aggregation value.
				</p>
				<p>
					The runtime evaluates the having-clause at the granularity of the data posted by data windows (if any) or when an event arrives (without a data windows). That is, if you utilize a time window and output every 10 events, the <code class="literal">having</code> clause applies to each individual event or events entering and leaving the time window (and not once per batch of 10 events).
				</p>
				<p>
					The <code class="literal">output</code> clause interacts in two ways with the <code class="literal">group by</code> and <code class="literal">having</code> clauses. First, in the <code class="literal">output every n events </code>case, the number <code class="literal">n</code> refers to the number of events arriving into the <code class="literal">group by clause</code>. That is, if the <code class="literal">group by</code> clause outputs only 1 event per group, or if the arriving events don't satisfy the <code class="literal">having</code> clause, then the actual number of events output by the statement could be fewer than <code class="literal">n</code>.
				</p>
				<p>
					Second, the <code class="literal">last</code>, <code class="literal">all</code> and <code class="literal">first</code> keywords have special meanings when used in a statement with aggregate functions and the <code class="literal">group by</code> clause:
				</p>
				<div class="itemizedlist">
					<ul compact="compact">
						<li>
							<p>
								When no keyword is specified, the runtime produces an output row for each row in the batch or when using group-by then an output per group only for those groups present in the batch, following <a class="xref" href="processingmodel.html#processingmodel_aggregation" title="2.15. Basic Aggregated Statement Types">Section 2.15, “Basic Aggregated Statement Types”</a>.
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">all</code> keyword (the default) specifies that the most recent data for <span class="emphasis"><em>all</em></span> groups seen so far should be output, whether or not these groups' aggregate values have just been updated
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">last</code> keyword specifies that only groups whose aggregate values have been updated with the most recent batch of events should be output.
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">first</code> keyword specifies that only groups whose aggregate values have been updated with the most recent batch of events should be output following the defined frequency, keeping frequency state for each group.
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">snapshot</code> keyword does not consider the recent batch and has special behavior as discussed in <a class="xref" href="epl_clauses.html#epl-output-snapshot" title="5.7.1.3. Output Snapshot">Section 5.7.1.3, “Output Snapshot”</a>.
							</p>
						</li>
					</ul>
				</div>
				<p>
					Please consult the <a class="xref" href="appendix_outputspec.html" title="Appendix A. Output Reference and Samples">Appendix A, <i>Output Reference and Samples</i></a> for detailed information on insert and remove stream output for aggregation and group-by.
				</p>
				<p>
					By adding an output rate limiting clause to a statement that contains a <span class="emphasis"><em>group by</em></span> clause you can control output of groups to obtain one row for each group, generating an event per group at the given output frequency.
				</p>
				<p>
					The next statement outputs total price per symbol cumulatively (no data window was used here). As it specifies the <code class="literal">all</code> keyword, the statement outputs the current value for all groups seen so far, regardless of whether the group was updated in the last interval. Output occurs after an interval of 5 seconds passed and at the end of each subsequent interval:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(price) from StockTickEvent group by symbol output all every 5 seconds</pre>
				<p>
					The below statement outputs total price per symbol considering events in the last 3 minutes. When events leave the 3-minute data window output also occurs as new aggregation values are computed. The <code class="literal">last</code> keyword instructs the runtime to output only those groups that had changes. Output occurs after an interval of 10 seconds passed and at the end of each subsequent interval:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(price) from StockTickEvent#time(3 min)
group by symbol output last every 10 seconds</pre>
				<p>
					This statement also outputs total price per symbol considering events in the last 3 minutes. The <code class="literal">first</code> keyword instructs the runtime to output as soon as there is a new value for a group. After output for a given group the runtime suppresses output for the same group for 10 seconds and does not suppress output for other groups. Output occurs again for that group after the interval when the group has new value(s):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(price) from StockTickEvent#time(3 min)
group by symbol output first every 10 seconds</pre>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-order-by"></a>5.8. Sorting Output: the <span class="emphasis"><em>Order By</em></span> Clause</h2>
					</div>
				</div>
			</div><a id="d0e10631" class="indexterm"></a><a id="d0e10634" class="indexterm"></a><a id="d0e10637" class="indexterm"></a><a id="d0e10640" class="indexterm"></a>
			<p>
				The <code class="literal">order by</code> clause is optional. It is used for ordering output events by their properties, or by expressions involving those properties. .
			</p>
			<p>
				For example, the following statement outputs batches of 5 or more stock tick events that are sorted first by price ascending and then by volume ascending:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol from StockTickEvent#time(60 sec) 
output every 5 events 
order by price, volume</pre>
			<p>
				Here is the syntax for the <code class="literal">order by</code> clause:
			</p>
			<pre class="synopsis">order by <span class="emphasis"><em>expression</em></span> [asc | desc] [, <span class="emphasis"><em>expression</em></span> [asc | desc]] [, ...]</pre>
			<p>
				If the <code class="literal">order by</code> clause is absent then the runtime still makes certain guarantees about the ordering of output:
			</p>
			<div class="itemizedlist">
				<ul compact="compact">
					<li>
						<p>
							If the statement is not a join, does not group via <code class="literal">group by</code> clause and does not declare grouped data windows via <code class="literal">#groupwin</code>, the order in which events are delivered to listeners and through the <code class="literal">iterator</code> pull API is the order of event arrival.
						</p>
					</li>
					<li>
						<p>
							If the statement is a join or outer join, or groups, then the order in which events are delivered to listeners and through the <code class="literal">iterator</code> pull API is not well-defined. Use the <code class="literal">order by</code> clause if your application requires events to be delivered in a well-defined order.
						</p>
					</li>
				</ul>
			</div>
			<p>
				The compiler places the following restrictions on the expressions in the <code class="literal">order by</code> clause:
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
				<ol>
					<li>
						<p>
							All aggregate functions that appear in the <code class="literal">order by</code> clause must also appear in the <code class="literal">select</code> expression.
						</p>
					</li>
				</ol>
			</div>
			<p>
				Otherwise, any kind of expression that can appear in the <code class="literal">select</code> clause,
				as well as any name defined in the <code class="literal">select</code> clause, is also valid in the order by clause.
			</p>
			<p>
				By default all sort operations on string values are performed via the <code class="literal">compare</code> method and are thus not locale dependent. To account for differences in language or locale, see <a class="xref" href="configuration.html#configuration-compiler-language" title="17.5.5. Compiler Settings Related to Language and Locale">Section 17.5.5, “Compiler Settings Related to Language and Locale”</a> to change this setting.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-limit"></a>5.9. Limiting Row Count: the <span class="emphasis"><em>Limit</em></span> Clause</h2>
					</div>
				</div>
			</div><a id="d0e10730" class="indexterm"></a><a id="d0e10733" class="indexterm"></a><a id="d0e10736" class="indexterm"></a><a id="d0e10739" class="indexterm"></a>
			<p>
				The <code class="literal">limit</code> clause is typically used together with the <code class="literal">order by</code> and <code class="literal">output</code> clause to limit your statement results to those that fall within a specified range. You can use it to receive the first given number of result rows, or to receive a range of result rows.
			</p>
			<p>
				There are two syntaxes for the <code class="literal">limit</code> clause, each can be parameterized by integer constants or by variable names. The first syntax is shown below:
			</p>
			<pre class="synopsis">limit <span class="emphasis"><em>row_count</em></span> [offset <span class="emphasis"><em>offset_count</em></span>]</pre>
			<p>
				The required <span class="emphasis"><em>row_count</em></span> parameter specifies the number of rows to output. The <span class="emphasis"><em>row_count</em></span> can be an integer constant
				and can also be the name of the integer-type variable to evaluate at runtime.
			</p>
			<p>
				The optional <span class="emphasis"><em>offset_count</em></span> parameter specifies the number of rows that should be skipped (offset) at the beginning of the result set. A variable can also be used for this parameter.
			</p>
			<p>
				The next sample statement outputs the top 10 counts per property 'uri' every 1 minute.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select uri, count(*) from WebEvent 
group by uri 
output snapshot every 1 minute
order by count(*) desc 
limit 10</pre>
			<p>
				The next statement demonstrates the use of the <code class="literal">offset</code> keyword. It outputs ranks 3 to 10 per property 'uri' every 1 minute:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select uri, count(*) from WebEvent 
group by uri 
output snapshot every 1 minute
order by count(*) desc 
limit 8 offset 2</pre>
			<p>
				The second syntax for the <code class="literal">limit</code> clause is for SQL standard compatibility and specifies the offset first, followed by the row count:
			</p>
			<pre class="synopsis">limit <span class="emphasis"><em>offset_count</em></span>[, <span class="emphasis"><em>row_count</em></span>]</pre>
			<p>
				The following are equivalent:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">limit 8 offset 2
// ...equivalent to
limit 2, 8</pre>
			<p>
				A negative value for <span class="emphasis"><em>row_count</em></span> returns an unlimited number or rows, and a zero value returns no rows. If variables are used, then the current variable value at the time of output dictates the row count and offset. A variable returning a null value for <span class="emphasis"><em>row_count</em></span> also returns an unlimited number or rows.
			</p>
			<p>
				A negative value for offset is not allowed. If your variable returns a negative or null value for offset then the value is assumed to be zero (i.e. no offset).
			</p>
			<p>
				The <code class="literal">iterator</code> pull API also honors the <code class="literal">limit</code> clause, if present.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-insert-into"></a>5.10. Merging Streams and Continuous Insertion: The <span class="emphasis"><em>Insert Into</em></span> Clause</h2>
					</div>
				</div>
			</div><a id="d0e10833" class="indexterm"></a><a id="d0e10836" class="indexterm"></a>
			<p>
				The <code class="literal">insert into</code> clause is optional in EPL. The clause can be specified to make the results of a statement available as an event stream for use
				in further statements, or to insert events into a named window or table. The clause can also be used to merge multiple event streams to form a single stream of events.
			</p>
			<p>
				The syntax for the <code class="literal">insert into</code> clause is as follows:
			</p>
			<pre class="synopsis">insert [istream | irstream | rstream] into <span class="emphasis"><em>event_stream_name</em></span>  [ ( [<span class="emphasis"><em>property_name</em></span> [, property_name]] ) ]
 [ event-precedence (<span class="emphasis"><em>precedence-expression</em></span>) ]</pre>
			<p>
				The <code class="literal">istream</code> (default) and <code class="literal">rstream</code> keywords are optional. If no keyword or the <code class="literal">istream</code> keyword is specified, the runtime supplies the insert stream events generated by the statement. The insert stream consists of the events entering the respective window(s) or stream(s). If the <code class="literal">rstream</code> keyword is specified, the runtime supplies the remove stream events generated by the statement. The remove stream consists of the events leaving the respective window(s).
			</p>
			<p>
				If your application specifies <code class="literal">irstream</code>, the runtime inserts into the new stream both the insert and remove stream. This is often useful in connection with the <code class="literal">istream</code> built-in function that returns an inserted/removed boolean indicator for each event, see <a class="xref" href="functionreference.html#epl-single-row-function-istream" title="10.1.11. The Istream Function">Section 10.1.11, “The Istream Function”</a>.
			</p>
			<p>
				The <code class="literal">event_stream_name</code> is an identifier that names the event stream (and also implicitly names the types of events in the stream) generated by the compiler.
				It may also specify a named window name or a table name.
				The identifier can be used in further statements to filter and process events of that event stream, unless inserting into a table.
				The <code class="literal">insert into</code> clause can consist of just an event stream name, or an event stream name and one or more property names.
			</p>
			<p>
				The <code class="literal">event-precedence</code> keyword and the <span class="emphasis"><em>precedence-expression</em></span> expression are for control over the order of processing of events that the <code class="literal">insert into</code>-clause produces. It is further explained in <a class="xref" href="epl_clauses.html#insert-into-eventprecedence" title="5.10.10. Insert Into and Event Precedence">Section 5.10.10, “Insert Into and Event Precedence”</a>.
			</p>
			<p>
				The runtime also allows listeners to be attached to a statement that contain an <code class="literal">insert into</code> clause. Listeners receive all events posted to the event stream.
			</p>
			<p>
				To merge event streams, simply use the same <code class="literal">event_stream_name</code> identifier in all statements that merge their result event streams. Make sure to use the
				same number and names of event properties and event property types match up.
			</p>
			<p>
				The compiler places the following restrictions on the <code class="literal">insert into</code> clause:
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
				<ol>
					<li>
						<p>
							The number of elements in the <code class="literal">select</code> clause must match the number of elements in the <code class="literal">insert into</code> clause if the clause specifies a list of event property names
						</p>
					</li>
					<li>
						<p>
							If the event stream name has already been defined by a prior statement or configuration, and the event property names and/or event types do not match, an exception is thrown at statement compile time.
						</p>
					</li>
				</ol>
			</div>
			<p>
				The following sample inserts into an event stream by name CombinedEvent:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into CombinedEvent
select A.customerId as custId, A.timestamp - B.timestamp as latency
  from EventA#time(30 min) A, EventB#time(30 min) B
 where A.txnId = B.txnId</pre>
			<p>
				Each event in the <code class="literal">CombinedEvent</code> event stream has two event properties named "custId" and "latency". The events generated by the above statement can be used in further statements, such as shown in the next statement:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select custId, sum(latency)
  from CombinedEvent#time(30 min)
 group by custId</pre>
			<p>
				The example statement below shows the alternative form of the <code class="literal">insert into</code> clause that explicitly defines the property names to use.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into CombinedEvent (custId, latency)
select A.customerId, A.timestamp - B.timestamp 
...</pre>
			<p>
				The <code class="literal">rstream</code> keyword can be useful to indicate to the runtime to generate only remove stream events. This can be useful if you want to trigger
				actions when events leave a window rather then when events enter a window. The statement below generates <code class="literal">CombinedEvent</code> events when
				EventA and EventB leave the window after 30 minutes.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert rstream into CombinedEvent
select A.customerId as custId, A.timestamp - B.timestamp as latency
  from EventA#time(30 min) A, EventB#time(30 min) B
 where A.txnId = B.txnId</pre>
			<p>
				The <code class="literal">insert into</code> clause can be used in connection with patterns to provide pattern results to further statements for analysis:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into ReUpEvent
select linkUp.ip as ip 
from pattern [every linkDown=LinkDownEvent -&gt; linkUp=LinkUpEvent(ip=linkDown.ip)]</pre>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-property-transpose"></a>5.10.1. Transposing a Property to a Stream</h3>
						</div>
					</div>
				</div>
				<p>
					Sometimes your events may carry properties that are themselves event objects. Therefore EPL offers a special syntax to insert the value of a property itself as an event into a stream:
				</p>
				<pre class="synopsis">insert into <span class="emphasis"><em>stream_name</em></span> select <span class="emphasis"><em>property_name</em></span>.* from ...</pre>
				<p>
					This feature is only supported for JavaBean events and for <code class="literal">Map</code> and Object-array (<code class="literal">Object[]</code>) event types that associate an event type name with the property type. It is not supported for <code class="literal">XML</code> events. Nested property names are also not supported.
				</p>
				<p>
					In this example, the class <code class="literal">Summary</code> with properties <code class="literal">bid</code> and <code class="literal">ask</code> that are of type <code class="literal">Quote</code> is:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class Summary {
  private Quote bid;
  private Quote ask;
  ...</pre>
				<p>
					The statement to populate a stream of <code class="literal">Quote</code> events is thus:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into MyBidStream select bid.* from Summary</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-merging-columns"></a>5.10.2. Merging Streams by Event Type</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">insert into</code> clause allows to merge multiple event streams into a event single stream.
					The clause names an event stream to insert into by specifing an <span class="emphasis"><em>event_stream_name</em></span>. The first statement that inserts into the named stream defines the stream's event types. Further statements that
					insert into the same event stream must match the type of events inserted into the stream as declared by the first statement.
				</p>
				<p>
					One approach to merging event streams specifies individual colum names either in the <code class="literal">select</code> clause or in the <code class="literal">insert into</code> clause of the statement. This approach has been shown in earlier examples.
				</p>
				<p>
					Another approach to merging event streams specifies the wildcard (*) in the <code class="literal">select</code> clause (or the stream wildcard) to select the underlying event. The events in the event stream must then
					have the same event type as generated by the <code class="literal">from</code> clause.
				</p>
				<p>
					Assume a statement creates an event stream named MergedStream by selecting OrderEvent events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into MergedStream select * from OrderEvent</pre>
				<p>
					A statement can use the stream wildcard selector to select only OrderEvent events in a join:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into MergedStream select ord.* from ItemScanEvent, OrderEvent as ord</pre>
				<p>
					And a statement may also use an application-supplied user-defined function to convert events to OrderEvent instances:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into MergedStream select MyLib.convert(item) from ItemScanEvent as item</pre>
				<p>
					The compiler specifically recognizes a conversion function as follows: A conversion function must be the only selected column, and it must return either a Java object or <code class="literal">java.util.Map</code> or <code class="literal">Object[]</code> (object array).
					Your EPL should not use the <code class="literal">as</code> keyword to assign a column name.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-merging-types"></a>5.10.3. Merging Disparate Types of Events: Variant Streams</h3>
						</div>
					</div>
				</div><a id="d0e11070" class="indexterm"></a>
				<p>
					A <span class="emphasis"><em>variant stream</em></span> is a predefined stream into which events of multiple disparate event types can be inserted.
				</p>
				<p>
					A variant stream name may appear anywhere in a pattern or <code class="literal">from</code> clause. In a pattern, a filter against a variant stream matches any events of any of the event types inserted into the variant stream.
					In a <code class="literal">from</code> clause including for named windows, data windows may hold events of any of the event types inserted into the variant stream.
				</p>
				<p>
					A variant stream is thus useful in problems that require different types of event to be treated the same.
				</p>
				<p>
					Variant streams can be declared by means of <code class="literal">create variant schema</code> or can be predefined via runtime or initialization-time configuration as described in <a class="xref" href="configuration.html#configuration-common-variantstream" title="17.4.16. Variant Stream">Section 17.4.16, “Variant Stream”</a>. Your application may declare or predefine variant streams to carry events of a limited set of event types, or you may choose the variant stream to carry any and all types of events. This choice affects what event properties are available for consuming statements or patterns of the variant stream.
				</p>
				<p>
					Assume that an application predefined a variant stream named <code class="literal">OrderStream</code> to carry only <code class="literal">ServiceOrder</code> and <code class="literal">ProductOrder</code> events. An <code class="literal">insert into</code> clause inserts events into
					the variant stream:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into OrderStream select * from ServiceOrder</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into OrderStream select * from ProductOrder</pre>
				<p>
					Here is a sample statement that consumes the variant stream and outputs a total price per customer id for the last 30 seconds of <code class="literal">ServiceOrder</code> and <code class="literal">ProductOrder</code> events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select customerId, sum(price) from OrderStream#time(30 sec) group by customerId</pre>
				<p>
					If your application predefines the variant stream to hold specific type of events, as the sample above did, then all event properties that are common to all specified types are visible on the variant stream, including nested, indexed and mapped properties. For access to properties that are only available on one of the types, the dynamic property syntax must be used. In the example above, the <code class="literal">customerId</code> and <code class="literal">price</code> were properties common to both <code class="literal">ServiceOrder</code> and <code class="literal">ProductOrder</code> events.
				</p>
				<p>
					For example, here is a consuming statement that selects a <code class="literal">service duraction</code> property that only <code class="literal">ServiceOrder</code> events have, and that must therefore be casted to double and null values removed in order to aggregate:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select customerId, sum(coalesce(cast(serviceDuraction?, double), 0)) 
from OrderStream#time(30 sec) group by customerId</pre>
				<p>
					If your application predefines a variant stream to hold any type of events (the <code class="literal">any</code> type variance), then all event properties of the variant stream are effectively dynamic properties.
				</p>
				<p>
					For example, an application may define an <code class="literal">OutgoingEvents</code> variant stream to hold any type of event. The next statement is a sample consumer of the <code class="literal">OutgoingEvents</code> variant stream that looks for the <code class="literal">destination</code> property and fires for each event in which the property exists with a value of <code class="literal">'email'</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from OutgoingEvents(destination = 'email')</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-decorated"></a>5.10.4. Decorated Events</h3>
						</div>
					</div>
				</div><a id="d0e11171" class="indexterm"></a>
				<p>
					Your <code class="literal">select</code> clause may use the '*' wildcard together with further expressions to populate a stream of events. A sample statement is:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into OrderStream select *, price*units as linePrice from PurchaseOrder</pre>
				<p>
					When using wildcard and selecting additional expression results, the runtime produces what is called <span class="emphasis"><em>decorating</em></span> events for the resulting stream. Decorating events add additional property values to an underlying event.
				</p>
				<p>
					In the above example the resulting OrderStream consists of underlying PurchaseOrder events <span class="emphasis"><em>decorated</em></span> by a <code class="literal">linePrice</code> property that is a result of the <code class="literal">price*units</code> expression.
				</p>
				<p>
					In order to use <code class="literal">insert into </code> to insert into an existing stream of decorated events, your underlying event type must match, and all additional decorating property names and types of the <code class="literal">select</code> clause must also match.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-eventasproperty"></a>5.10.5. Event as a Property</h3>
						</div>
					</div>
				</div><a id="d0e11208" class="indexterm"></a>
				<p>
					Your <code class="literal">select</code> clause may use the stream name to populate a stream of events in which each event has properties that are itself an event. A sample statement is:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into CompositeStream select order, service, order.price+service.price as totalPrice 
from PurchaseOrder#lastevent as order, ServiceEvent#lastevent as service</pre>
				<p>
					When using the stream name (or tag in patterns) in the select-clause, the runtime produces composite events: One or more of the properties of the composite event are events themselves.
				</p>
				<p>
					In the above example the resulting CompositeStream consists of 3 columns: the PurchaseOrder event, the ServiceEvent event and the <code class="literal">totalPrice</code> property that is a result of the <code class="literal">order.price+service.price</code> expression.
				</p>
				<p>
					In order to use <code class="literal">insert into </code> to insert into an existing stream of events in which properties are themselves events, each event column's event type must match, and all additional property names and types of the <code class="literal">select</code> clause must also match.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-populate"></a>5.10.6. Instantiating and Populating an Underlying Event Object</h3>
						</div>
					</div>
				</div>
				<p>
					Your <code class="literal">insert into</code> clause may also directly instantiate and populate application underlying event objects or <code class="literal">Map</code> or <code class="literal">Object[]</code> event objects. This is described in greater detail in <a class="xref" href="event_representation.html#eventrep-insertinto" title="3.9. Event Objects Instantiated and Populated by Insert Into">Section 3.9, “Event Objects Instantiated and Populated by Insert Into”</a>.
				</p>
				<p>
					If instead you have an expression that returns an event object, please read on to the next section.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-expression"></a>5.10.7. Transposing an Expression Result</h3>
						</div>
					</div>
				</div>
				<p>
					You can transpose an object returned as an expression result into a stream using the <code class="literal">transpose</code> function as described further in <a class="xref" href="functionreference.html#functionreference-transpose" title="10.4. Select-Clause Transpose Function">Section 10.4, “Select-Clause Transpose Function”</a>.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-reconcile"></a>5.10.8. Select-Clause Expression and Inserted-Into Column Event Type</h3>
						</div>
					</div>
				</div>
				<p>
					When you declare the inserted-into event type in advance to the statement that inserts, the runtime compares the inserted-into event type information to the return type of expressions in the select-clause.
					The comparison uses the column alias assigned to each select-clause expression using the <code class="literal">as</code> keyword.
				</p>
				<p>
					When the inserted-into column type is an event type and when using a subquery or the <code class="literal">new</code> operator,
					the runtime compares column names assigned to subquery columns or <code class="literal">new</code> operator columns.
				</p>
				<p>
					For example, assume a <code class="literal">PurchaseOrder</code> event type that has a property called <code class="literal">items</code> that consists of <code class="literal">Item</code> rows:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema Item(name string, price double)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema PurchaseOrder(orderId string, items Item[])</pre>
				<p>
					Declare a statement that inserts into the <code class="literal">PurchaseOrder</code> stream:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into PurchaseOrder 
select '001' as orderId, new {name='i1', price=10} as items
from TriggerEvent</pre>
				<p>
					The alias assigned to the first and second expression in the select-clause, namely <code class="literal">orderId</code> and <code class="literal">items</code>,
					both match the event property names of the <code class="literal">Purchase Order</code> event type. The column names provided to the <code class="literal">new</code> operator
					also both match the event property names of the <code class="literal">Item</code> event type.
				</p>
				<p>
					When the event type declares the column as a single value (and not an array) and when the select-clause expression produces a multiple rows,
					the runtime only populate the first row.
				</p>
				<p>
					Consider a <code class="literal">PurchaseOrder</code> event type that has a property called <code class="literal">item</code> that consists of a single <code class="literal">Item</code> event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema PurchaseOrder(orderId string, items Item)</pre>
				<p>
					The sample subquery below populates only the very first event, discarding remaining subquery result events, since the <code class="literal">items</code> property above is declared as holding a single <code class="literal">Item</code>-typed event only (versus <code class="literal">Item[]</code> to hold multiple <code class="literal">Item</code>-typed events).
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into PurchaseOrder select 
(select 'i1' as name, 10 as price from HistoryEvent#length(2)) as items 
from TriggerEvent</pre>
				<p>
					Consider using a subquery with filter, or one of the enumeration methods to select a specific subquery result row.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-typewithoutprops"></a>5.10.9. Insert Into for Event Types Without Properties</h3>
						</div>
					</div>
				</div>
				<p>
					When using insert-into and the type information for the inserted-into stream exists and the type has no properties, specify a <code class="literal">select</code>-clause that selects a single column of value <code class="literal">null</code> and that provides no column name.
				</p>
				<p>
					For example, the next EPL declares a <code class="literal">TriggerStream</code> type that has no event properties:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema TriggerStream ()</pre>
				<p>
					To populate events of type <code class="literal">TriggerStream</code>, let the <code class="literal">select</code>-clause simply select <code class="literal">null</code>, like this:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into TriggerStream select null from ... </pre>
				<p>
					This example uses a pattern to populate a <code class="literal">TrggerStream</code> event every 10 seconds:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into TriggerStream select null from pattern[every timer:interval(10 sec)]</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="insert-into-eventprecedence"></a>5.10.10. Insert Into and Event Precedence</h3>
						</div>
					</div>
				</div>
				<p>
					As part of the <code class="literal">insert into</code> clause the optional <code class="literal">event-precedence</code> keyword allows specifying an expression that returns an
					event precedence value that applies to the inserted event. The value controls the order in which the runtime processes the inserted event as compared to other inserted events
					that are yet to be processed.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="warning">
					<h2>Warning</h2>
					<p>
						In order to use event precedence you must set the precedence-enabled flag in the runtime configuration.
						Please refer to <a class="xref" href="configuration.html#configuration-runtime-execution-eventprecedence" title="17.6.10.2. Event-Precedence Execution">Section 17.6.10.2, “Event-Precedence Execution”</a>.
					</p>
				</div>
				<p>
					The event precedence expression must return an integer-type value. The expression may return negative values.
					The default precedence is zero (<code class="literal">0</code>) and applies when there is no <code class="literal">event-precedence</code>-clause or when the event-precedence expression returns a <code class="literal">null</code>-value.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						The event precedence expression can use properties of the insert-into generated event and may use wildcard to mean the inserted event.
					</p>
					<p>
						The expression cannot use properties of <code class="literal">from</code>-clause or <code class="literal">on</code>-clause events.
					</p>
				</div>
				<p>
					To illustrate the concept of event precedence, consider two example event types <code class="literal">InputEvent</code> and <code class="literal">FurtherEvent</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@public @buseventtype create schema InputEvent(name string);
@public create schema FurtherEvent(id string);</pre>
				<p>
					Here is a statement that, upon an <code class="literal">InputEvent</code>, produces two events of type <code class="literal">FurtherEvent</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on InputEvent 
  insert into FurtherEvent select 'id-1' as id
  insert into FurtherEvent select 'id-2' as id
  output all;</pre>
				<p>
					The above statement does not specify an event-precedence and therefore the runtime processes the <code class="literal">FurtherEvent</code> events in the order they are generated.
					So the runtime first processes the <code class="literal">InputEvent</code>, and then the <code class="literal">FurtherEvent={id='id-1'}</code> and then the <code class="literal">FurtherEvent={id='id-2'}</code>, in that order.
				</p>
				<p>
					The next example assigns a precedence value of <code class="literal">1</code> to <code class="literal">FurtherEvent={id='id-1'}</code> and a precedence value of <code class="literal">2</code> to <code class="literal">FurtherEvent={id='id-2'}</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on InputEvent 
  insert into FurtherEvent event-precedence(1) select 'id-1' as id
  insert into FurtherEvent event-precedence(2) select 'id-2' as id
  output all</pre>
				<p>
					The precedence values instruct the runtime to process <code class="literal">FurtherEvent={id='id-2'}</code> first, and then <code class="literal">FurtherEvent={id='id-1'}</code> (higher precedence value first).
				</p>
				<p>
					The precedence can be computed. The below statement determines the precedence value based on the value of the <code class="literal">name</code> property of the inserted event.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into FurtherEvent event-precedence(case when name = 'Joe' then 1 else 2 end)
  select name, 'id-a' as id from InputEvent;</pre>
				<p>
					For further information on runtime event processing order, please read <a class="xref" href="apiruntime.html#apiruntime-processingorder-eventdepth" title="16.8.2.2. Processing Principles of Events and Listener Updates">Section 16.8.2.2, “Processing Principles of Events and Listener Updates”</a>.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-subqueries"></a>5.11. Subqueries</h2>
					</div>
				</div>
			</div><a id="d0e11500" class="indexterm"></a><a id="d0e11503" class="indexterm"></a>
			<p>
				A subquery is a <code class="literal">select</code> within another statement. The compiler supports subqueries in the <code class="literal">select</code> clause, <code class="literal">where</code> clause, <code class="literal">having</code> clause and in stream and pattern filter expressions. Subqueries provide an alternative way to perform operations that would otherwise require complex joins. Subqueries can also make statements more readable then complex joins.
			</p>
			<p>
				EPL supports both simple subqueries as well as correlated subqueries. In a simple subquery, the inner query is not correlated to the outer query. Here is an example simple subquery within a <code class="literal">select</code> clause:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetId, (select zone from ZoneClosed#lastevent) as lastClosed from RFIDEvent</pre>
			<p>
				If the inner query is dependent on the outer query, you will have a correlated subquery. An example of a correlated subquery is shown below. Notice the <code class="literal">where</code> clause in the inner query, where the condition involves a stream from the outer query:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent as RFID where 'Dock 1' = 
  (select name from Zones#unique(zoneId) where zoneId = RFID.zoneId)</pre>
			<p>
				The example above shows a subquery in the <code class="literal">where</code> clause. The statement selects RFID events in which the zone name matches a string constant based on zone id. The statement sets <code class="literal">#unique</code> to guarantee that only the last event per zone id is retained for processing by the subquery.
			</p>
			<p>
				The next example is a correlated subquery within a <code class="literal">select</code> clause. In this statement the <code class="literal">select</code> clause retrieves the zone name by means of a subquery against the Zones set of events correlated by zone id:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select zoneId, (select name from Zones#unique(zoneId) 
  where zoneId = RFID.zoneId) as name from RFIDEvent</pre>
			<p>
				Note that when a simple or correlated subquery returns multiple rows, the runtime returns a <code class="literal">null</code> value as the subquery result. To limit the number of events returned by a subquery consider using one of the <code class="literal">#lastevent</code>, <code class="literal">#unique</code> data windows or aggregation functions or the multi-row and multi-column-select as described below.
			</p>
			<p>
				The <code class="literal">select</code> clause of a subquery also allows wildcard selects, which return as an event property the underlying event object of the event type as defined in the <code class="literal">from</code> clause. An example:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select (select * from MarketData#lastevent) as md 
  from pattern [every timer:interval(10 sec)]</pre>
			<p>
				The output events to the statement above contain the underlying MarketData event in a property named "md". The statement populates the last MarketData event into a property named "md" every 10 seconds following the pattern definition, or populates a <code class="literal">null</code> value if no MarketData event has been encountered so far.
			</p>
			<p>
				Aggregation functions may be used in the <code class="literal">select</code> clause of the subselect as this example outlines:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MarketData
where price &gt; (select max(price) from MarketData(symbol='GOOG')#lastevent)</pre>
			<p>
				As the sub-select expression is evaluated first (by default), the query above actually never fires for the GOOG symbol, only for other symbols that have a price higher then the current maximum for GOOG. As a sidenote, the <code class="literal">insert into</code> clause can also be handy to compute aggregation results for use in multiple subqueries.
			</p>
			<p>
				When using aggregation functions in a correlated subselect the runtime computes the aggregation based on data window (if provided), named window or table contents matching the where-clause (correlated subquery aggregations are not incrementally computed).
			</p>
			<p>
				The following example compares the quantity value provided by the current order event against the total quantity of all order events in the last 1 hour for the same client.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from OrderEvent oe
where qty &gt; 
  (select sum(qty) from OrderEvent#time(1 hour) pd 
  where pd.client = oe.client)</pre>
			<p>
				Filter expressions in a pattern or stream may also employ subqueries. Subqueries can be uncorrelated or can be correlated to properties of the stream or to properties of tagged events in a pattern. Subqueries may reference named windows and tables as well.
			</p>
			<p>
				The following example filters <code class="literal">BarData</code> events that have a close price less then the last moving average (field <code class="literal">movAgv</code>) as provided by stream <code class="literal">SMA20Stream</code> (an uncorrelated subquery):
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from BarData(ticker='MSFT', closePrice &lt; 
    (select movAgv from SMA20Stream(ticker='MSFT')#lastevent))</pre>
			<p>
				A few generic examples follow to demonstrate the point. The examples use short event and property names so they are easy to read. Assume <code class="literal">A</code> and <code class="literal">B</code> are streams and <code class="literal">DNamedWindow</code> is a named window, and <code class="literal">ETable</code> is a table and properties <code class="literal">a_id, b_id, d_id, e_id, a_val, b_val, d_val, e_val</code> respectively:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Sample correlated subquery as part of stream filter criteria
select * from A(a_val in 
  (select b_val from B#unique(b_val) as b where a.a_id = b.b_id)) as a</pre>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Sample correlated subquery against a named window
select * from A(a_val in 
  (select d_val from DNamedWindow as d where a.a_id = d.d_id)) as a</pre>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Sample correlated subquery in the filter criteria as part of a pattern, querying a named window
select * from pattern [
  a=A -&gt; b=B(bvalue = 
    (select d_val from DNamedWindow as d where d.d_id = b.b_id and d.d_id = a.a_id))
]</pre>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Sample correlated subquery against a table
select * from A(a_val in 
  (select e_val from ETable as e where a.a_id = e.e_id)) as a</pre>
			<p>
				Subquery state starts to accumulate as soon as a statement starts (and not only when a pattern-subexpression activates).
			</p>
			<p>
				The following restrictions apply to subqueries:
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
				<ol>
					<li>
						<p>
							Subqueries can only consist of a <code class="literal">select</code> clause, a <code class="literal">from</code> clause, a <code class="literal">where</code> clause, a <code class="literal">group by</code> clause and a <code class="literal">having</code> clause. Joins, outer-joins and output rate limiting are not permitted within subqueries.
						</p>
					</li>
					<li>
						<p>
							If using aggregation functions in a subquery, note these limitations:
						</p>
						<div class="orderedlist">
							<ol>
								<li>
									<p>
										None of the properties of the correlated stream(s) can be used within aggregation functions.
									</p>
								</li>
								<li>
									<p>
										The properties of the subselect stream must all be within aggregation functions.
									</p>
								</li>
							</ol>
						</div>
					</li>
					<li>
						<p>
							With the exception of subqueries against named windows and tables and subqueries that are both uncorrelated and fully-aggregated,
							the subquery stream definition must define a data window to limit subquery results, for the purpose of identifying the events held for subquery execution.
						</p>
					</li>
					<li>
						<p>
							The <code class="literal">having</code>-clause, if present, requires that properties of the selected stream are aggregated and does not allow un-aggregated properties of the selected stream.
							You may use the <code class="literal">first</code> aggregation function to obtain properties of the selected stream instead.
						</p>
					</li>
				</ol>
			</div>
			<p>
				The order of evaluation of subqueries relative to the containing statement is guaranteed: If the containing statement and its subqueries are reacting to the same type of event, the subquery will receive the
				event first before the containing statement's clauses are evaluated. This behavior can be changed via configuration. The order of evaluation of subqueries is not guaranteed between subqueries.
			</p>
			<p>
				Performance of your statement containing one or more subqueries principally depends on two parameters. First, if your subquery correlates one or more columns in the subquery stream with the enclosing statement's streams, the compiler determines and the runtime automatically builds the appropriate indexes for fast row retrieval based on the key values correlated (joined). The second parameter is the number of rows found in the subquery stream and the complexity of the filter criteria (<code class="literal">where</code> clause), as each row in the subquery stream must evaluate against the <code class="literal">where</code> clause filter.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-subqueries-exists"></a>5.11.1. The '<code class="literal">Exists</code>' Keyword</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">exists</code> condition is considered "to be met" if the subquery returns at least one row. The <code class="literal">not exists</code> condition is considered true if the subquery returns no rows.
				</p>
				<p>
					The synopsis for the <code class="literal">exists</code> keyword is as follows:
				</p>
				<pre class="synopsis">exists (<span class="emphasis"><em>subquery</em></span>)</pre>
				<p>
					Let's take a look at a simple example. The following is a statement that uses the <code class="literal">exists</code> condition:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetId from RFIDEvent as RFID 
  where exists (select * from Asset#unique(assetId) where assetId = RFID.assetId)</pre>
				<p>
					This select statement will return all RFID events where there is at least one event in Assets unique by asset id with the same asset id.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-subqueries-in"></a>5.11.2. The '<code class="literal">In</code>' and '<code class="literal">Not In</code>' Keywords</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">in</code> subquery condition is true if the value of an expression matches one or more of the values returned by the subquery. Consequently, the <code class="literal">not in</code> condition is true if the value of an expression matches none of the values returned by the subquery.
				</p>
				<p>
					The synopsis for the <code class="literal">in</code> keyword is as follows:
				</p>
				<pre class="synopsis"><span class="emphasis"><em>expression</em></span> in (<span class="emphasis"><em>subquery</em></span>)</pre>
				<p>
					The right-hand side subquery must return exactly one column.
				</p>
				<p>
					The next statement demonstrates the use of the <code class="literal">in</code> subquery condition:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetId from RFIDEvent
  where zone in (select zone from ZoneUpdate(status = 'closed')#time(10 min))</pre>
				<p>
					The above statement demonstrated the <code class="literal">in</code> subquery to select RFID events for which the zone status is in a closed state.
				</p>
				<p>
					Note that if the left-hand expression yields null, or if there are no equal right-hand values and at least one right-hand row yields null, the result of the <code class="literal">in</code> construct will be null, not false (or true for <code class="literal">not-in</code>). This is in accordance with SQL's normal rules for Boolean combinations of null values.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-subqueries-anysome"></a>5.11.3. The '<code class="literal">Any</code>' and '<code class="literal">Some</code>' Keywords</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">any</code> subquery condition is true if the expression returns true for one or more of the values returned by the subquery.
				</p>
				<p>
					The synopsis for the <code class="literal">any</code> keyword is as follows:
				</p>
				<pre class="synopsis"><span class="emphasis"><em>expression</em></span> <span class="emphasis"><em>operator</em></span> any (<span class="emphasis"><em>subquery</em></span>)
<span class="emphasis"><em>expression</em></span> <span class="emphasis"><em>operator</em></span> some (<span class="emphasis"><em>subquery</em></span>)</pre>
				<p>
					The left-hand expression is evaluated and compared to each row of the subquery result using the given operator, which must yield a Boolean result. The result of <code class="literal">any</code> is "true" if any true result is obtained. The result is "false" if no true result is found (including the special case where the subquery returns no rows).
				</p>
				<p>
					The <span class="emphasis"><em>operator</em></span> can be any of the following values: <code class="literal">=, !=, &lt;&gt;, &lt;, &lt;=, &gt;, &gt;=</code>.
				</p>
				<p>
					The <code class="literal">some</code> keyword is a synonym for <code class="literal">any</code>. The <code class="literal">in</code> construct is equivalent to <code class="literal">= any</code>.
				</p>
				<p>
					The right-hand side subquery must return exactly one column.
				</p>
				<p>
					The next statement demonstrates the use of the <code class="literal">any</code> subquery condition:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from ProductOrder as ord
  where quantity &lt; any
    (select minimumQuantity from MinimumQuantity#keepall)</pre>
				<p>
					The above statement compares ProductOrder event's quantity value with all rows from the MinimumQuantity stream of events and returns only those ProductOrder events that have a quantity that is less then any of the minimum quantity values of the MinimumQuantity events.
				</p>
				<p>
					Note that if there are no successes and at least one right-hand row yields null for the operator's result, the result of the <code class="literal">any</code> construct will be null, not false. This is in accordance with SQL's normal rules for Boolean combinations of null values.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-subqueries-all"></a>5.11.4. The '<code class="literal">All</code>' Keyword</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">all</code> subquery condition is true if the expression returns true for all of the values returned by the subquery.
				</p>
				<p>
					The synopsis for the <code class="literal">all</code> keyword is as follows:
				</p>
				<pre class="synopsis"><span class="emphasis"><em>expression</em></span> <span class="emphasis"><em>operator</em></span> all (<span class="emphasis"><em>subquery</em></span>)</pre>
				<p>
					The left-hand expression is evaluated and compared to each row of the subquery result using the given operator, which must yield a Boolean result. The result of <code class="literal">all</code> is "true" if all rows yield true (including the special case where the subquery returns no rows). The result is "false" if any false result is found. The result is <code class="literal">null</code> if the comparison does not return false for any row, and it returns <code class="literal">null</code> for at least one row.
				</p>
				<p>
					The <span class="emphasis"><em>operator</em></span> can be any of the following values: <code class="literal">=, !=, &lt;&gt;, &lt;, &lt;=, &gt;, &gt;=</code>.
				</p>
				<p>
					The <code class="literal">not in</code> construct is equivalent to <code class="literal">!= all</code>.
				</p>
				<p>
					The right-hand side subquery must return exactly one column.
				</p>
				<p>
					The next statement demonstrates the use of the <code class="literal">all</code> subquery condition:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from ProductOrder as ord
  where quantity &lt; all
    (select minimumQuantity from MinimumQuantity#keepall)</pre>
				<p>
					The above statement compares ProductOrder event's quantity value with all rows from the MinimumQuantity stream of events and returns only those ProductOrder events that have a quantity that is less then all of the minimum quantity values of the MinimumQuantity events.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-subqueries-groupby"></a>5.11.5. Subquery With <code class="literal">Group By</code> Clause</h3>
						</div>
					</div>
				</div>
				<p>
					The optional <code class="literal">group by</code> clause in subqueries works the same way as the group-by clause outside of subqueries,
					except that it impacts only those aggregations within the subquery.
				</p>
				<p>
					The following restrictions apply:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Expressions in the group-by clause cannot contain aggregate functions, subqueries or the <code class="literal">prev</code> and <code class="literal">prior</code> functions.
							</p>
						</li>
						<li>
							<p>
								Subqueries only support the fully-aggregated case when using group-by: All non-aggregated properties in the select clause must be listed in the group by clause.
							</p>
						</li>
						<li>
							<p>
								The group-by expressions cannot be correlated. All properties in the <code class="literal">group by</code> must be provided by the subselect stream.
							</p>
						</li>
					</ol>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-subqueries-multicolumn"></a>5.11.6. Multi-Column Selection</h3>
						</div>
					</div>
				</div>
				<p>
					Your subquery may select multiple columns in the <code class="literal">select</code> clause including multiple aggregated values from a data window or named window or table.
				</p>
				<p>
					The following example is a correlated subquery that selects wildcard and in addition selects the <code class="literal">bid</code> and <code class="literal">offer</code> properties of the last <code class="literal">MarketData</code> event for the same symbol as the arriving <code class="literal">OrderEvent</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select *,
  (select bid, offer from MarketData#unique(symbol) as md 
   where md.symbol = oe.symbol) as bidoffer
from OrderEvent oe</pre>
				<p>
					Output events for the above statement contain all properties of the original <code class="literal">OrderEvent</code> event. In addition each output event contains a <code class="literal">bidoffer</code> nested property that itself contains the <code class="literal">bid</code> and <code class="literal">offer</code> properties. You may retrieve the bid and offer from output events directly via the <code class="literal">bidoffer.bid</code> property name syntax for nested properties.
				</p>
				<p>
					The next example is similar to the above statement but instead selects aggregations and selects from a named window by name <code class="literal">OrderNamedWindow</code> (creation not shown here). For each arriving <code class="literal">OrderEvent</code> it selects the total quantity and count of all order events for the same client, as currently held by the named window:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select *,
  (select sum(qty) as sumPrice, count(*) as countRows 
   from OrderNamedWindow as onw
   where onw.client = oe.client) as pastOrderTotals
from OrderEvent as oe</pre>
				<p>
					The next statement computes a prorated quantity considering the maximum and minimum quantity for the last 1 minute of order events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression subq {
  (select max(quantity) as maxq, min(quantity) as minq from OrderEvent#time(1 min))
}
select (quantity - minq) / (subq().maxq  - subq().minq) as prorated
from OrderEvent</pre>
				<p>
					Output events for the above statement contain all properties of the original <code class="literal">OrderEvent</code> event. In addition each output event contains a <code class="literal">pastOrderTotals</code> nested property that itself contains the <code class="literal">sumPrice</code> and <code class="literal">countRows</code> properties.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-subqueries-multirow"></a>5.11.7. Multi-Row Selection</h3>
						</div>
					</div>
				</div>
				<p>
					While a subquery cannot change the cardinality of the selected stream, a subquery can return multiple values from the selected data window or named window or table. This section shows examples of the <code class="literal">window</code> aggregation function as well as the use of enumeration methods with subselects.
				</p>
				<p>
					Consider using an inner join, outer join or unidirectional join instead to achieve a 1-to-many cardinality in the number of output events.
				</p>
				<p>
					The next example is an uncorrelated subquery that selects all current <code class="literal">ZoneEvent</code> events considering the last <code class="literal">ZoneEvent</code> per zone for each arriving <code class="literal">RFIDEvent</code>.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetId,
 (select window(z.*) as winzones from ZoneEvent#unique(zone) as z) as zones
 from RFIDEvent</pre>
				<p>
					Output events for the above statement contain two properties: the <code class="literal">assetId</code> property and the <code class="literal">zones</code> property. The latter property is a nested property that contains the <code class="literal">winzones</code> property. You may retrieve the zones from output events directly via the <code class="literal">zones.winzones</code> property name syntax for nested properties.
				</p>
				<p>
					In this example for a correlated subquery against a named window, assume that the <code class="literal">OrderNamedWindow</code> has been created and contains order events. The statement returns for each <code class="literal">MarketData</code> event
					the list of order ids for orders with the same symbol:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select price,
 (select window(orderId) as winorders 
  from OrderNamedWindow onw 
  where onw.symbol = md.symbol) as orderIds
 from MarketData md</pre>
				<p>
					Output events for the above statement contain two properties: the <code class="literal">price</code> property and the <code class="literal">orderIds</code> property. The latter property is a nested property that contains the <code class="literal">winorders</code> property of type array.
				</p>
				<p>
					Another option to reduce selected rows to a single value is through the use of enumeration methods.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select price,
 (select *  from OrderNamedWindow onw
  where onw.symbol = md.symbol).selectFrom(v =&gt; v) as ordersSymbol
 from MarketData md</pre>
				<p>
					Output events for the above statement also contain a Collection of underlying events in the <code class="literal">ordersSymbol</code> property.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-subqueries-hints"></a>5.11.8. Hints Related to Subqueries</h3>
						</div>
					</div>
				</div>
				<p>
					The following hints are available to tune performance and memory use of subqueries.
				</p>
				<p>
					Use the <code class="literal">@Hint('set_noindex')</code> hint for a statement that utilizes one or more subqueries. It instructs the runtime to always perform a full scan. The runtime does not build an implicit index or use an explicitly-created index when this hint is provided. Use of the hint may result in reduced memory use but poor statement performance.
				</p>
				<p>
					The following hints are available to tune performance and memory use of subqueries that select from named windows (does not apply to tables).
				</p>
				<p>
					Named windows are globally-visible data windows. As such an application may create explicit indexes as discussed in <a class="xref" href="nwtable.html#named_explicit_index" title="6.9. Explicitly Indexing Named Windows and Tables">Section 6.9, “Explicitly Indexing Named Windows and Tables”</a>. The runtime may also elect to create implicit indexes (no create-index EPL required) for index-based lookup of rows when executing <code class="literal">on-select</code>, <code class="literal">on-merge</code>, <code class="literal">on-update</code> and <code class="literal">on-delete</code> statements and for statements that subquery a named window.
				</p>
				<p>
					By default and without specifying a hint, each statement that subqueries a named window also maintains its own index for looking up events held by the named window.
					The runtime maintains the index by consuming the named window insert and remove stream. When the statement is undeployed it releases that index.
				</p>
				<p>
					Specify the <code class="literal">@Hint('enable_window_subquery_indexshare')</code> hint to enable subquery index sharing for named windows. When using this hint, indexes for subqueries are maintained by the named window itself (and not each statement context partition).
					However only indexes explictly created with <code class="literal">create index</code> are used in this case. Specify the hint once as part of the <code class="literal">create window</code> statement.
				</p>
				<p>
					This sample statement creates a named window with subquery index sharing enabled:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hint('enable_window_subquery_indexshare')
create window OrdersNamedWindow#keepall as OrderMapEventType</pre>
				<p>
					When subquery index sharing is enabled, performance may increase as named window stream consumption is no longer needed for correlated subqueries. You may also expect reduced memory use especially if a large number of statements perform similar subqueries against a named window. Subquery index sharing may require additional short-lived object creation and may slightly increase lock held time for named windows.
				</p>
				<p>
					The following statement performs a correlated subquery against the named window above. When a settlement event arrives it select the order detail for the same order id as provided by the settlement event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 
  (select * from OrdersNamedWindow as onw 
    where onw.orderId = se.orderId) as orderDetail
  from SettlementEvent as se</pre>
				<p>
					With subquery index sharing enabled and only when a suitable index exists the query planner uses the index. A sample index is:
				</p><code class="literal">create index MyIndex on OrdersNamedWindow(orderId)</code>
				<p>
					You may disable subquery index sharing for a specific statement by specifying the <code class="literal">@Hint('disable_window_subquery_indexshare')</code> hint, as this example shows, causing the statement to maintain its own index:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hint('disable_window_subquery_indexshare')
select 
  (select * from OrdersNamedWindow as onw 
    where onw.orderId = se.orderId) as orderDetail
  from SettlementEvent as se</pre>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-join"></a>5.12. Joining Event Streams</h2>
					</div>
				</div>
			</div><a id="d0e12155" class="indexterm"></a><a id="d0e12158" class="indexterm"></a>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-join-introducing"></a>5.12.1. Introducing Joins</h3>
						</div>
					</div>
				</div>
				<p>
					Two or more event streams can be part of the <code class="literal">from</code>-clause and thus both (all) streams determine the resulting events. This section summarizes the important concepts. The sections that follow present more detail on each topic.
				</p>
				<p>
					The default join is an inner join which produces output events only when there is at least one match in all streams.
				</p>
				<p>
					Consider the sample statement shown next:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent#lastevent, NewsEvent#lastevent</pre>
				<p>
					The above statement outputs the last TickEvent and the last NewsEvent in one output event when either a TickEvent or a NewsEvent arrives. If no TickEvent was received before a NewsEvent arrives, no output occurs. Similarly when no NewsEvent was received before a TickEvent arrives, no output occurs.
				</p>
				<p>
					The <code class="literal">where</code>-clause lists the join conditions that the compiler uses to relate events in the two or more streams.
				</p>
				<p>
					The next example statement retains the last TickEvent and last NewsEvent per symbol, and joins the two streams based on their symbol value:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent#unique(symbol) as t, NewsEvent#unique(symbol) as n
where t.symbol = n.symbol</pre>
				<p>
					As before, when a TickEvent arrives for a symbol that has no matching NewsEvent then there is no output event.
				</p>
				<p>
					An outer join does not require each event in either stream to have a matching event. The full outer join is useful when output is desired when no match is found. The different outer join types (full, left, right) are explained in more detail below.
				</p>
				<p>
					This example statement is an outer-join and also returns the last TickEvent and last NewsEvent per symbol:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent#unique(symbol) as t
full outer join NewsEvent#unique(symbol) as n on t.symbol = n.symbol</pre>
				<p>
					In the sample statement above, when a TickEvent arrives for a symbol that has no matching NewsEvent, or when a NewsEvent arrives for a symbol that has no matching TickEvent, the statement still produces an output event with a null column value for the missing event.
				</p>
				<p>
					Note that each of the sample statements above defines a data window. The sample statements above use the last-event data window (#lastevent) or the unique data window (#unique). A data window serves to indicate the subset of events to join from each stream and may be required depending on the join.
				</p>
				<p>
					In above statements, when either a TickEvent arrives or when a NewsEvent arrives then the statement evaluates and there is output. The same holds true if additional streams are added to the <code class="literal">from</code>-clause: Each of the streams in the <code class="literal">from</code>-clause trigger the join to evaluate.
				</p>
				<p>
					The <code class="literal">unidirectional</code> keyword instructs the runtime to evaluate the join only when an event arrives from the single stream that was marked with the <code class="literal">unidirectional</code> keyword. In this case no data window should be specified for the stream marked as <code class="literal">unidirectional</code> since the keyword implies that the current event of that stream triggers the join.
				</p>
				<p>
					Here is the sample statement above with <code class="literal">unidirectional</code> keyword, so that output occurs only when a TickEvent arrives and not when a NewsEvent arrives:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent as t unidirectional, NewsEvent#unique(symbol) as n 
where t.symbol = n.symbol</pre>
				<p>
					It is oftentimes the case that an aggregation (count, sum, average) only needs to be calculated in the context of an arriving event or timer. Consider using the <code class="literal">unidirectional</code> keyword when aggregating over joined streams.
				</p>
				<p>
					An EPL pattern is a normal citizen also providing a stream of data consisting of pattern matches. A time pattern, for example, can be useful to evaluate a join and produce output upon each interval.
				</p>
				<p>
					This sample statement includes a pattern that fires every 5 seconds and thus triggers the join to evaluate and produce output, computing an aggregated total quantity per symbol every 5 seconds:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(qty) from pattern[every timer:interval(5 sec)] unidirectional, 
  TickEvent#unique(symbol) t, NewsEvent#unique(symbol) as n 
where t.symbol = n.symbol group by symbol</pre>
				<p>
					Named windows as well as reference and historical data such as stored in your relational database, and data returned by a method/script/UDF invocation, can also be included in joins as discussed in <a class="xref" href="epl_clauses.html#histdata_overview" title="5.13. Accessing Relational Data via SQL">Section 5.13, “Accessing Relational Data via SQL”</a> and <a class="xref" href="epl_clauses.html#joining_method" title="5.14. Accessing Non-Relational Data via Method, Script or UDF Invocation">Section 5.14, “Accessing Non-Relational Data via Method, Script or UDF Invocation”</a>.
				</p>
				<p>
					Related to joins are subqueries: A subquery is a <code class="literal">select</code> within another statement, see <a class="xref" href="epl_clauses.html#epl-subqueries" title="5.11. Subqueries">Section 5.11, “Subqueries”</a>
				</p>
				<p>
					The compiler performs extensive statement analysis and planning, building internal indexes and strategies as required to allow fast evaluation of many types of statements.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-join-inner"></a>5.12.2. Inner (Default) Joins</h3>
						</div>
					</div>
				</div>
				<p>
					Each point in time that an event arrives to one of the event streams, the two event streams are joined and output events are produced according to the <code class="literal">where</code> clause when matching events are found for all joined streams.
				</p>
				<p>
					This example joins 2 event streams. The first event stream consists of fraud warning events for which it keep the last 30 minutes. The second stream is withdrawal events for which it considers the last 30 seconds. The streams are joined on account number.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select fraud.accountNumber as accntNum, fraud.warning as warn, withdraw.amount as amount,
       max(fraud.timestamp, withdraw.timestamp) as timestamp, 'withdrawlFraud' as desc
  from FraudWarningEvent#time(30 min) as fraud, WithdrawalEvent#time(30 sec) as withdraw
 where fraud.accountNumber = withdraw.accountNumber</pre>
				<p>
					Joins can also include one or more pattern statements as the next example shows:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from FraudWarningEvent#time(30 min) as fraud,
    pattern [every w=WithdrawalEvent -&gt; PINChangeEvent(acct=w.acct)]#lastevent as withdraw
 where fraud.accountNumber = withdraw.w.accountNumber</pre>
				<p>
					The statement above joins the last 30 minutes of fraud warnings with a pattern. The pattern consists of every withdrawal event that is followed by a PIN change event for the same account number. It joins the two event streams on account number. The last-event window instucts the join to only consider the last pattern match.
				</p>
				<p>
					In a join and outer join, your statement must declare a data window onto each stream. Streams that are marked as unidirectional and named windows and tables as well as database or methods in a join are an exception and do not require a data window. If you are joining an event to itself via contained-event selection, data windows also do not need to be specified. The reason that a data window must be declared is that a data window specifies which events are considered for the join (i.e. last event, last 10 events, all events, last 1 second of events etc.).
				</p>
				<p>
					The next example joins all FraudWarningEvent events that arrived since the statement was started, with the last 20 seconds of PINChangeEvent events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from FraudWarningEvent#keepall as fraud, PINChangeEvent#time(20 sec) as pin
 where fraud.accountNumber = pin.accountNumber</pre>
				<p>
					The above example employed the special keep-all window that retains all events.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-outerjoin"></a>5.12.3. Outer, Left and Right Joins</h3>
						</div>
					</div>
				</div><a id="d0e12281" class="indexterm"></a><a id="d0e12284" class="indexterm"></a><a id="d0e12287" class="indexterm"></a><a id="d0e12292" class="indexterm"></a>
				<p>
					EPL supports left outer joins, right outer joins, full outer joins and inner joins in any combination between an unlimited number of event streams. Outer and inner joins can also join reference and historical data as explained in <a class="xref" href="epl_clauses.html#histdata_overview" title="5.13. Accessing Relational Data via SQL">Section 5.13, “Accessing Relational Data via SQL”</a>, as well as join data returned by a method, script or UDF invocation as outlined in <a class="xref" href="epl_clauses.html#joining_method" title="5.14. Accessing Non-Relational Data via Method, Script or UDF Invocation">Section 5.14, “Accessing Non-Relational Data via Method, Script or UDF Invocation”</a>.
				</p>
				<p>
					The keywords <code class="literal">left, right, full</code> and <code class="literal">inner</code> control the type of the join between two streams. The optional <code class="literal">on</code> clause specifies one or more properties that join each stream. The synopsis is as follows:
				</p>
				<pre class="synopsis">...from <span class="emphasis"><em>stream_def</em></span> [as name] 
  ((left|right|full outer) | inner) join <span class="emphasis"><em>stream_def</em></span> 
  [on <span class="emphasis"><em>property</em></span> = <span class="emphasis"><em>property</em></span> [and <span class="emphasis"><em>property</em></span> = <span class="emphasis"><em>property</em></span> ...] ]
  [ ((left|right|full outer) | inner) join <span class="emphasis"><em>stream_def</em></span> [on ...]]...
</pre>
				<p>
					If the outer join is a left outer join, there will be at least one output event for each event of the stream on the left-hand side of the clause. For example, in the left outer join shown below you get output for each event in the stream RfidEvent, even if the event does not match any event in the event stream OrderList.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent#time(30 sec) as rfid
       left outer join
       OrderList#length(10000) as orderlist
     on rfid.itemId = orderList.itemId</pre>
				<p>
					Similarly, if the join is a Right Outer Join, then there will be at least one output event for each event of the stream on the right-hand side of the clause. For example, in the right outer join shown below you get output for each event in the stream OrderList, even if the event does not match any event in the event stream RfidEvent.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent#time(30 sec) as rfid
       right outer join
       OrderList#length(10000) as orderlist
       on rfid.itemId = orderList.itemId</pre>
				<p>
					For all types of outer joins, if the join condition is not met, the select list is computed with the event properties of the arrived event while all other event properties are considered to be null.
				</p>
				<p>
					The next type of outer join is a full outer join. In a full outer join, each point in time that an event arrives to one of the event streams, one or more output events are produced. In the example below, when either an RfidEvent or an OrderList event arrive, one or more output event is produced. The next example shows a full outer join that joins on multiple properties:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent#time(30 sec) as rfid
       full outer join
       OrderList#length(10000) as orderlist
       on rfid.itemId = orderList.itemId and rfid.assetId = orderList.assetId</pre>
				<p>
					The last type of join is an inner join. In an inner join, the runtime produces at least one output event for each event of the stream on the left-hand side that matches at least one event on the right hand side considering the join properties. For example, in the inner join shown below you get output for each event in the RfidEvent stream that matches one or more events in the OrderList data window:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent#time(30 sec) as rfid
       inner join
       OrderList#length(10000) as orderlist
       on rfid.itemId = orderList.itemId and rfid.assetId = orderList.assetId</pre>
				<p>
					Patterns as streams in a join follow this rule: If your statement does not specify a data window for the pattern then the pattern stream retains the last match. Thus a pattern must have matched at least once for the last match to become available in a join. Multiple rows from a pattern stream may be retained by declaring a data window onto a pattern using the <code class="literal">pattern [...]#</code><span class="emphasis"><em>window_spec</em></span> syntax.
				</p>
				<p>
					This example outer joins multiple streams. Here the RfidEvent stream is outer joined to both ProductName and LocationDescription via left outer join:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RfidEvent#time(30 sec) as rfid
      left outer join ProductName#keepall as refprod
        on rfid.productId = refprod.prodId
      left outer join LocationDescription#keepall as refdesc
        on rfid.location = refdesc.locId</pre>
				<p>
					If the optional <code class="literal">on</code> clause is specified, it may only employ the <code class="literal">=</code> equals operator and property names. Any other operators must be placed in the <code class="literal">where</code>-clause.
					The stream names that appear in the <code class="literal">on</code> clause may refer to any stream in the <code class="literal">from</code>-clause.
				</p>
				<p>
					Your EPL may also provide no <code class="literal">on</code> clause. This is useful when the streams that are joined do not provide any properties to join on, for example when joining with a time-based pattern.
				</p>
				<p>
					The next example employs a unidirectional left outer join such that the runtime, every 10 seconds, outputs a count of the number of RfidEvent events in the 60-second time window.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*) from
  pattern[every timer:interval(1)] unidirectional 
  left outer join
  RfidEvent#time(60 sec)</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-unidirectional"></a>5.12.4. Unidirectional Joins</h3>
						</div>
					</div>
				</div><a id="d0e12395" class="indexterm"></a><a id="d0e12398" class="indexterm"></a><a id="d0e12403" class="indexterm"></a>
				<p>
					In a join or outer join your statement lists multiple event streams, data windows and/or patterns in the <code class="literal">from</code> clause. As events arrive into the runtime, each of the streams (data windows, patterns) provides insert and remove stream events. The runtime evaluates each insert and remove stream event provided by each stream, and joins or outer joins each event against data window contents of each stream, and thus generates insert and remove stream join results.
				</p>
				<p>
					The direction of the join execution depends on which stream or streams are currently providing an insert or remove stream event for executing the join.
					A join is thus multidirectional, or bidirectional when only two streams are joined.
					A join can be made unidirectional if your application does not want new results when events arrive on a given stream or streams.
				</p>
				<p>
					The <code class="literal">unidirectional</code> keyword can be used in the <code class="literal">from</code> clause to identify streams that provide the events to execute the join. If the keyword is present for a stream, all other streams in the <code class="literal">from</code> clause become passive streams. When events arrive or leave a data window of a passive stream then the join does not generate join results.
				</p>
				<p>
					For example, consider a use case that requires us to join stock tick events (TickEvent) and news events (NewsEvent). The <code class="literal">unidirectional</code> keyword allows to generate results only when TickEvent events arrive, and not when NewsEvent arrive or leave the 10-second time window:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent unidirectional, NewsEvent#time(10 sec) 
where tick.symbol = news.symbol</pre>
				<p>
					Aggregation functions in a <code class="literal">unidirectional</code> join aggregate within the context of each unidirectional event evaluation and are not cumulative. Thereby aggregation functions when used with <code class="literal">unidirectional</code> may evaluate faster as they do not need to consider a remove stream (data removed from data windows or named windows).
				</p>
				<p>
					The count function in the next statement returns, for each TickEvent, the number of matching NewEvent events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*) from TickEvent unidirectional, NewsEvent#time(10 sec) 
where tick.symbol = news.symbol</pre>
				<p>
					The following restrictions apply to unidirectional joins:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								The <code class="literal">unidirectional</code> keyword can only be specified for a single stream in the <code class="literal">from</code> clause, unless all streams are in a full outer join and all streams declare <code class="literal">unidirectional</code>.
							</p>
						</li>
						<li>
							<p>
								Receiving data from a unidirectional join via the pull API (<code class="literal">iterator</code> method) is not allowed. This is because the runtime holds no state for the single stream that provides the events to execute the join.
							</p>
						</li>
						<li>
							<p>
								The stream that declares the <code class="literal">unidirectional</code> keyword cannot declare a data window for that stream, since remove stream events are not processed for the single stream.
							</p>
						</li>
					</ol>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-unidirectional-fullouterjoin"></a>5.12.5. Unidirectional Full Outer Joins</h3>
						</div>
					</div>
				</div><a id="d0e12475" class="indexterm"></a><a id="d0e12478" class="indexterm"></a>
				<p>
					In a full outer join all streams can be marked as <code class="literal">unidirectional</code>.
					This is useful for declaring multiple triggering events and for performing a union or merge of streams.
				</p>
				<p>
					When marking more than one stream as unidirectional, all streams must be unidirectional and inner, left and right joins are not allowed.
					This is because unidirectional streams have an undefined depth and cannot be looked-up against.
				</p>
				<p>
					For example, consider a use case where output should occur when either a tick event or a news event arrives:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent as te unidirectional, 
  full outer join
  NewsEvent as ne unidirectional</pre>
				<p>
					Place filter criteria for a given stream into parenthesis, for example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent(symbol='IBM') unidirectional, 
  full outer join
  TradeEvent(symbol='IBM') unidirectional
  full outer join
  SettlementEvent(symbol='IBM') unidirectional
  where coalesce(TickEvent.price,TradeEvent.price) &gt; 100 // place common critera into a where-clause that may use coalesce</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-join-hints"></a>5.12.6. Hints Related to Joins</h3>
						</div>
					</div>
				</div>
				<p>
					When joining 3 or more streams (including any relational or non-relational sources as below) it can sometimes help to provide the query planner instructions how to best execute the join. The compiler compiles a query plan for the statement. You can output the query plan to logging (see configuration).
				</p>
				<p>
					An outer join that specifies only <code class="literal">inner</code> keywords for all streams is equivalent to an default (inner) join. The following two statements are equivalent:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent#lastevent, 
    NewsEvent#lastevent where tick.symbol = news.symbol</pre>
				<p>
					Equivalent to:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TickEvent#lastevent 
	inner join NewsEvent#lastevent on tick.symbol = news.symbol</pre>
				<p>
					For all types of joins, the query planner determines a query graph: The term is used here for all the information regarding what properties or expressions are used to join the streams. The query graph thus includes the where-clause expressions as well as outer-join on-clauses if this statement is an outer join. The query planner also computes a dependency graph which includes information about all historical data streams (relational and non-relational as below) and their input needs.
				</p>
				<p>
					For default (inner) joins the query planner first attempts to find a path of execution as a nested iteration. For each stream the query planner selects the best order of streams available for the nested iteration considering the query graph and dependency graph. If the full depth of the join is achievable via nested iteration for all streams without full table scan then the query planner uses that nested iteration plan. If not, then the query planner re-plans considering a merge join (Cartesian) approach instead.
				</p>
				<p>
					Specify the @Hint('prefer_merge_join') to instruct the query planner to prefer a merge join plan instead of a nested iteration plan. Specify the @Hint('force_nested_iter') to instruct the query planner to always use a nested iteration plan.
				</p>
				<p>
					For example, consider the below statement. Depending on the number of matching rows in OrderBookOne and OrderBookTwo (named windows in this example, and assumed to be defined elsewhere) the performance of the join may be better using the merge join plan.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hint('prefer_merge_join') 
select * from TickEvent#lastevent t, 
	OrderBookOne ob1, OrderBookOne ob2
where ob1.symbol = t.symbol and ob2.symbol = t.symbol 
and ob1.price between t.buy and t.sell and ob2.price between t.buy and t.sell</pre>
				<p>
					For outer joins the query planner considers nested iteration and merge join (Cartesian) equally and above hints don't apply.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="histdata_overview"></a>5.13. Accessing Relational Data via SQL</h2>
					</div>
				</div>
			</div><a id="d0e12529" class="indexterm"></a><a id="d0e12532" class="indexterm"></a><a id="d0e12537" class="indexterm"></a><a id="d0e12540" class="indexterm"></a>
			<p>
				For NEsper .NET also see <a class="xref" href="appendix_dotnet.html#appendix_dotnet_histdata_overview" title="J.14. .NET Accessing Relational Data via SQL">Section J.14, “.NET Accessing Relational Data via SQL”</a>.
			</p>
			<p>
				This chapter outlines how reference data and historical data that are stored in a relational database can be queried via SQL within statements.
			</p>
			<p>
				EPL can access via join and outer join as well as via iterator (poll) API all types of event streams to stored data. In order for such data sources to become accessible to EPL, some configuration is required. The <a class="xref" href="configuration.html#configuration-common-databaseref" title="17.4.12. Relational Database Access">Section 17.4.12, “Relational Database Access”</a> explains the required configuration for database access in greater detail, and includes information on configuring a query result cache.
			</p>
			<p>
				The compiler does not parse or otherwise inspect your SQL query. Therefore your SQL can make use of any database-specific SQL language extensions or features that your database provides.
			</p>
			<p>
				If you have enabled SQL query result caching in your database configuration, the runtime retains SQL query results in cache following the configured cache eviction policy.
			</p>
			<p>
				Also if you have enabled SQL query result caching in your database configuration and provide EPL <code class="literal">where</code> clause and/or <code class="literal">on</code> clause (outer join) expressions, then
				the runtime builds indexes on the SQL query results to enable fast lookup. This is especially useful if your SQL queries return a large number of rows. For building the proper indexes, the compiler inspects the expression found in your statement <code class="literal">where</code> clause, if present. For outer joins, the compiler also inspects your statement <code class="literal">on</code> clause. The compiler analyzes the EPL <code class="literal">on</code> clause and <code class="literal">where</code> clause expressions, if present, looking for property comparison with or without logical AND-relationships between properties. When a SQL query returns rows for caching, the runtime builds and caches the appropriate index and lookup strategies for fast row matching against indexes.
			</p>
			<p>
				Joins or outer joins in which only SQL statements or method, script and UDF invocations are listed in the <code class="literal">from</code> clause and no other event streams are termed <span class="emphasis"><em>passive</em></span> joins. A passive join does not produce an insert or remove stream and therefore does not invoke statement listeners with results. A passive join can be iterated on (polled) using a statement's <code class="literal">safeIterator</code> and <code class="literal">iterator</code> methods.
			</p>
			<p>
				There are no restrictions to the number of SQL statements or types of streams joined. The following restrictions currently apply:
			</p>
			<div class="itemizedlist">
				<ul compact="compact">
					<li>
						<p>
							An SQL query cannot declare data windows; That is, you cannot create a time or length window on an SQL query. Instead, use <code class="literal">insert into</code> to make join results available for further processing.
						</p>
					</li>
					<li>
						<p>
							Your database software must support JDBC prepared statements that provide statement meta data at compilation time. Most major databases provide this function. A workaround is available for databases that do not provide this function.
						</p>
					</li>
					<li>
						<p>
							JDBC drivers must support the getMetadata feature. A workaround is available as below for JDBC drivers that don't support getting metadata.
						</p>
					</li>
				</ul>
			</div>
			<p>
				The next sections assume basic knowledge of SQL (Structured Query Language).
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_join"></a>5.13.1. Joining SQL Query Results</h3>
						</div>
					</div>
				</div>
				<p>
					To join an event stream against stored data, specify the <code class="literal">sql</code> keyword followed by the name of the database and a parameterized SQL query. The syntax to use in the <code class="literal">from</code> clause of a statement is:
				</p>
				<pre class="synopsis">sql:<span class="emphasis"><em>database_name</em></span> [" <span class="emphasis"><em>parameterized_sql_query</em></span> "]</pre>
				<p>
					The runtime uses the <span class="emphasis"><em>database_name</em></span> identifier to obtain configuration information in order to establish a database connection, as well as settings that control connection creation and removal. Please see <a class="xref" href="configuration.html#configuration-common-databaseref" title="17.4.12. Relational Database Access">Section 17.4.12, “Relational Database Access”</a> to configure an runtime for database access.
				</p>
				<p>
					Following the database name is the SQL query to execute. The SQL query can contain one or more substitution parameters. The SQL query string is placed in single brackets <code class="literal">[</code> and <code class="literal">]</code>. The SQL query can be placed in either single quotes (') or double quotes ("). The SQL query grammer is passed to your database software unchanged, allowing you to write any SQL query syntax that your database understands, including stored procedure calls.
				</p>
				<p>
					Substitution parameters in the SQL query string take the form <code class="literal">${</code><span class="emphasis"><em>expression</em></span><code class="literal">}</code>. The compiler resolves <span class="emphasis"><em>expression</em></span> at statement execution time to the actual expression result by evaluating the events in the joined event stream or current variable values, if any event property references or variables occur in the expression. An <span class="emphasis"><em>expression</em></span> may not contain EPL substitution parameters.
				</p>
				<p>
					The compiler determines the type of the SQL query output columns by means of the result set metadata that your database software returns for the statement. The actual
					SQL query results are obtained via the <code class="literal">getObject</code> on <code class="literal">java.sql.ResultSet</code>.
				</p>
				<p>
					The sample statement below joins an event stream consisting of <code class="literal">CustomerCallEvent</code> events with the results of an SQL query against the database named <code class="literal">MyCustomerDB</code> and table <code class="literal">Customer</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select custId, cust_name from CustomerCallEvent,
  sql:MyCustomerDB [' select cust_name from Customer where cust_id = ${custId} ']</pre>
				<p>
					The example above assumes that <code class="literal">CustomerCallEvent</code> supplies an event property named <code class="literal">custId</code>. The SQL query selects the customer name from the Customer table. The <code class="literal">where</code> clause in the SQL matches the Customer table column <code class="literal">cust_id</code> with the value of <code class="literal">custId</code> in each <code class="literal">CustomerCallEvent</code> event. The runtime executes the SQL query for each new <code class="literal">CustomerCallEvent</code> encountered.
				</p>
				<p>
					If the SQL query returns no rows for a given customer id, the runtime generates no output event. Else the runtime generates one output event for each row returned by the SQL query. An outer join as described in the next section can be used to control whether the runtime should generate output events even when the SQL query returns no rows.
				</p>
				<p>
					The next example adds a time window of 30 seconds to the event stream <code class="literal">CustomerCallEvent</code>. It also renames the selected properties to customerName and customerId to demonstrate how the naming of columns in an SQL query can be used in the <code class="literal">select</code> clause in the statement. And the example uses explicit stream names via the <code class="literal">as</code> keyword.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select customerId, customerName from
  CustomerCallEvent#time(30 sec) as cce,
  sql:MyCustomerDB ["select cust_id as customerId, cust_name as customerName from Customer 
                  where cust_id = ${cce.custId}"] as cq</pre>
				<p>
					Any window, such as the time window, generates insert stream (istream) events as events enter the window, and remove stream (rstream) events as events leave the window. The runtime executes the given SQL query for each <code class="literal">CustomerCallEvent</code> in both the insert stream and the remove stream. As a performance optimization, the <code class="literal">istream</code> or <code class="literal">rstream</code> keywords in the <code class="literal">select</code> clause can be used to instruct the runtime to only join insert stream or remove stream events, reducing the number of SQL query executions.
				</p>
				<p>
					Since any expression may be placed within the <code class="literal">${...}</code> syntax, you may use variables or user-defined functions as well.
				</p>
				<p>
					The next example assumes that a variable by name <code class="literal">varLowerLimit</code> is defined and that a user-defined function <code class="literal">getLimit</code> exists on the <code class="literal">MyLib</code> imported class that takes a <code class="literal">LimitEvent</code> as a parameter:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from LimitEvent le, 
  sql:MyCustomerDB [' select cust_name from Customer where 
      amount &gt; ${max(varLowerLimit, MyLib.getLimit(le))} ']</pre>
				<p>
					The example above takes the higher of the current variable value or the value returned by the user-defined function to return only those customer names where the amount exceeds the computed limit.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_join_where"></a>5.13.2. SQL Query and the EPL <code class="literal">Where</code> Clause</h3>
						</div>
					</div>
				</div>
				<p>
					Consider using the EPL <code class="literal">where</code> clause to join the SQL query result to your event stream. Similar to EPL joins and outer-joins that join event streams or patterns, the EPL <code class="literal">where</code> clause provides join criteria between the SQL query results and the event stream (as a side note, an SQL <code class="literal">where</code> clause is a filter of rows executed by your database on your database server before returning SQL query results).
				</p>
				<p>
					The compiler analyzes the expression in the EPL <code class="literal">where</code> clause and outer-join <code class="literal">on</code> clause, if present, and builds the appropriate indexes from that information at runtime, to ensure fast matching of event stream events to SQL query results, even if your SQL query returns a large number of rows. Your applications must ensure to configure a cache for your database using configuration, as such indexes are held with regular data in a cache. If your application does not enable caching of SQL query results, the runtime does not build indexes on cached data.
				</p>
				<p>
					The sample statement below joins an event stream consisting of <code class="literal">OrderEvent</code> events with the results of an SQL query against the database named <code class="literal">MyRefDB</code> and table <code class="literal">SymbolReference</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, symbolDesc from OrderEvent as orders,
  sql:MyRefDB ['select symbolDesc from SymbolReference'] as reference
  where reference.symbol = orders.symbol</pre>
				<p>
					Notice how the EPL <code class="literal">where</code> clause joins the <code class="literal">OrderEvent</code> stream to the <code class="literal">SymbolReference</code> table. In this example, the SQL query itself does not have a SQL <code class="literal">where</code> clause
					and therefore returns all rows from table <code class="literal">SymbolReference</code>.
				</p>
				<p>
					If your application enables caching, the SQL query fires only at the arrival of the first <code class="literal">OrderEvent</code> event. When the second <code class="literal">OrderEvent</code> arrives, the join execution uses the cached SQL query result. If the caching policy that you specified in the database configuration evicts the SQL query result from cache, then the runtime fires the SQL query again to obtain a new result and places the result in cache.
				</p>
				<p>
					If SQL result caching is enabled and your EPL <code class="literal">where</code> clause, as show in the above example, provides the properties to join, then the runtime indexes the SQL query results in cache and retains the index together with the SQL query result in cache. Thus your application can benefit from high performance index-based lookups as long as the SQL query results are found in cache.
				</p>
				<p>
					The SQL result caches operate on the level of all result rows for a given parameter set. For example, if your SQL query returns 10 rows for a certain set of parameter values then the cache treats all 10 rows as a single entry keyed by the parameter values, and the expiry policy applies to all 10 rows and not to each individual row.
				</p>
				<p>
					It is also possible to join multiple autonomous database systems in a single statement, for example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, symbolDesc from OrderEvent as orders,
  sql:My_Oracle_DB ['select symbolDesc from SymbolReference'] as reference,
  sql:My_MySQL_DB ['select orderList from orderHistory'] as history
  where reference.symbol = orders.symbol
  and history.symbol = orders.symbol </pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_outerjoin"></a>5.13.3. Outer Joins With SQL Queries</h3>
						</div>
					</div>
				</div>
				<p>
					You can use outer joins to join data obtained from an SQL query and control when an event is produced. Use a left outer join, such as in the next statement, if you need an output event for each event regardless of whether or not the SQL query returns rows. If the SQL query returns no rows, the join result populates null values into the selected properties.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select custId, custName from
  CustomerCallEvent as cce
  left outer join 
  sql:MyCustomerDB ["select cust_id, cust_name as custName 
                     from Customer where cust_id = ${cce.custId}"] as cq
  on cce.custId = cq.cust_id</pre>
				<p>
					The statement above always generates at least one output event for each <code class="literal">CustomerCallEvent</code>, containing all columns selected by the SQL query, even if the SQL query does not return any rows. Note the <code class="literal">on</code> expression that is required for outer joins. The <code class="literal">on</code> acts as an additional filter to rows returned by the SQL query.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_polling_pattern"></a>5.13.4. Using Patterns to Request (Poll) Data</h3>
						</div>
					</div>
				</div>
				<p>
					Pattern statements and SQL queries can also be applied together in useful ways. One such use is to poll or request data from a database at regular intervals or following the schedule of the crontab-like <code class="literal">timer:at</code>.
				</p>
				<p>
					The next statement is an example that shows a pattern that fires every 5 seconds to query the NewOrder table for new orders:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into NewOrders
select orderId, orderAmount from
  pattern [every timer:interval(5 sec)],
  sql:MyCustomerDB ['select orderId, orderAmount from NewOrders']</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_polling"></a>5.13.5. Polling SQL Queries via Iterator</h3>
						</div>
					</div>
				</div>
				<p>
					Usually your SQL query will take part in a join and thus be triggered by an event or pattern occurrence. Instead, your application may need to poll a SQL query and thus use runtime statement execution and caching facilities and obtain event data and metadata.
				</p>
				<p>
					Your statement can specify an SQL statement without a join. Such a stand-alone SQL statement does not post new events, and may only be queried via the <code class="literal">iterator</code> poll API. Your EPL and SQL statement may still use variables.
				</p>
				<p>
					The next statement assumes that a <code class="literal">price_var</code> variable has been declared. It selects from the relational database table named <code class="literal">NewOrder</code> all rows in which the <code class="literal">price</code> column is greater
					then the current value of the <code class="literal">price_var</code> EPL variable:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from sql:MyCustomerDB ['select * from NewOrder where ${price_var} &gt; price']</pre>
				<p>
					Use the <code class="literal">iterator</code> and <code class="literal">safeIterator</code> methods on <code class="literal">EPStatement</code> to obtain results. The statement does not post events to listeners, it is strictly passive in that sense.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_implementation"></a>5.13.6. JDBC Implementation Overview</h3>
						</div>
					</div>
				</div>
				<p>
					The runtime translates SQL queries into JDBC <code class="literal">java.sql.PreparedStatement</code> statements by replacing ${name} parameters with '?' placeholders. It obtains name and type of result columns from the compiled <code class="literal">PreparedStatement</code> meta data when the statement gets compiled.
				</p>
				<p>
					The runtime supplies parameters to the compiled statement via the <code class="literal">setObject</code> method on <code class="literal">PreparedStatement</code>. The runtime uses the <code class="literal">getObject</code> method on the compiled statement <code class="literal">PreparedStatement</code> to obtain column values.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_nometadata"></a>5.13.7. Oracle Drivers and No-Metadata Workaround</h3>
						</div>
					</div>
				</div>
				<p>
					Certain JDBC database drivers are known to not return metadata for precompiled prepared SQL statements. This can be a problem as metadata is required by the compiler. The compiler obtains SQL result set metadata to validate a statement and to provide column types for output events. JDBC drivers that do not provide metadata for precompiled SQL statements require a workaround. Such drivers do generally provide metadata for executed SQL statements, however do not provide the metadata for precompiled SQL statements.
				</p>
				<p>
					Please consult the <a class="xref" href="configuration.html" title="Chapter 17. Configuration">Chapter 17, <i>Configuration</i></a> for the configuration options available in relation to metadata retrieval.
				</p>
				<p>
					To obtain metadata for an SQL statement, the compiler can alternatively fire a SQL statement which returns the same column names and types as the actual SQL statement but without returning any rows. This kind of SQL statement is referred to as a <span class="emphasis"><em>sample</em></span> statement in below workaround description. The compiler can then use the sample SQL statement to retrieve metadata for the column names and types returned by the actual SQL statement.
				</p>
				<p>
					Applications can provide a sample SQL statement to retrieve metadata via the <code class="literal">metadatasql</code> keyword:
				</p>
				<pre class="synopsis">sql:<span class="emphasis"><em>database_name</em></span> ["<span class="emphasis"><em>parameterized_sql_query</em></span>" metadatasql "<span class="emphasis"><em>sql_meta_query</em></span>"] </pre>
				<p>
					The <span class="emphasis"><em>sql_meta_query</em></span> must be an SQL statement that returns the same number of columns, the same type of columns and the same column names as the
					<span class="emphasis"><em>parameterized_sql_query</em></span>, and does not return any rows.
				</p>
				<p>
					Alternatively, applications can choose not to provide an explicit sample SQL statement. If the statement does not use the <code class="literal">metadatasql</code> syntax, the compiler applies lexical analysis to the SQL statement. From the lexical analysis the compiler generates a sample SQL statement adding a restrictive clause "where 1=0" to the SQL statement.
				</p>
				<p>
					Alternatively, you can add the following tag to the SQL statement: <code class="literal">${$ESPER-SAMPLE-WHERE}</code>. If the tag exists in the SQL statement, the compiler does not perform lexical analysis and simply replaces the
					tag with the SQL <code class="literal">where</code> clause "where 1=0". Therefore this workaround is applicable to SQL statements that cannot be correctly lexically analyzed. The SQL text after the placeholder is not part of the sample SQL query. For example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select mycol from sql:myDB [
  'select mycol from mytesttable ${$ESPER-SAMPLE-WHERE} where ....'], ...</pre>
				<p>
					If your <span class="emphasis"><em>parameterized_sql_query</em></span> SQL query contains vendor-specific SQL syntax, generation of the metadata query may fail to produce a valid SQL statement. If you experience an SQL error while fetching metadata, use any of the above workarounds with the Oracle JDBC driver.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_convert_cols"></a>5.13.8. SQL Input Parameter and Column Output Conversion</h3>
						</div>
					</div>
				</div>
				<p>
					As part of database access configuration you may optionally specify SQL type mappings. These mappings apply to all SQL queries against the same database identified by name.
				</p>
				<p>
					If your application must perform SQL-query-specific or EPL-statement-specific mapping or conversion between types, the facility to register a conversion callback exists as follows.
				</p>
				<p>
					Use the <code class="literal">@Hook</code> instruction and <code class="literal">HookType.SQLCOL</code> as part of your statement to register a statement SQL parameter or column conversion hook.
					Implement the interface <code class="literal">com.espertech.esper.common.client.hook.type.SQLColumnTypeConversion</code> to perform the input parameter or column value conversion.
				</p>
				<p>
					A sample statement with annotation is shown:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hook(type=HookType.SQLCOL, hook='MyDBTypeConvertor')
select * from sql:MyDB ['select * from MyEventTable]</pre>
				<p>
					The compiler expects <code class="literal">MyDBTypeConvertor</code> to resolve to a class (considering imports) and instantiates one instance of MyDBTypeConvertor for each statement.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_convert_row"></a>5.13.9. SQL Row POJO Conversion</h3>
						</div>
					</div>
				</div>
				<p>
					Your application may also directly convert a SQL result row into a Java class which is an opportunity for your application to interrogate and transform the SQL row result data freely before packing the data into a
					Java class. Your application can additionally indicate to skip SQL result rows.
				</p>
				<p>
					Use the <code class="literal">@Hook</code> instruction and <code class="literal">HookType.SQLROW</code> as part of your statement to register a statement SQL output row conversion hook.
					Implement the interface <code class="literal">com.espertech.esper.common.client.hook.type.SQLOutputRowConversion</code> to perform the output row conversion.
				</p>
				<p>
					A sample statement with annotation is shown:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Hook(type=HookType.SQLROW, hook='MyDBRowConvertor')
select * from sql:MyDB ['select * from MyEventTable]</pre>
				<p>
					The compiler expects <code class="literal">MyDBRowConvertor</code> to resolve to a class (considering imports) and instantiates one MyDBRowConvertor instance for each statement.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="histdata_fireandforget"></a>5.13.10. Executing SQL Fire-and-Forget Queries Using <code class="literal">EPFireAndForgetService</code></h3>
						</div>
					</div>
				</div>
				<p>
					The Esper fire-and-forget query API provides a facility to execute on-demand one-time queries and such queries can query a relational database.
					The Esper runtime executes SQL queries and returns the results as events - thereby an application can avoid using the JDBC API.
					For further information please refer to <a class="xref" href="apiruntime.html#apiruntime-fireandforget-fromcansql" title="16.7.5. The From-Clause can Access Relational Data via SQL">Section 16.7.5, “The From-Clause can Access Relational Data via SQL”</a>.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="joining_method"></a>5.14. Accessing Non-Relational Data via Method, Script or UDF Invocation</h2>
					</div>
				</div>
			</div><a id="d0e13043" class="indexterm"></a><a id="d0e13048" class="indexterm"></a>
			<p>
				Your application may need to join data that originates from a web service, a distributed cache, an object-oriented database or simply data held in memory by your application.
				One way to join in external data is by means of method, script or user-defined function invocation (or procedure call or function) in the <code class="literal">from</code> clause of a statement.
			</p>
			<p>
				The results of such a method, script or UDF invocation in the <code class="literal">from</code> clause plays the same role as a relational database table in an inner and outer join in SQL.
			</p>
			<p>
				EPL can join and outer join an unlimited number and all types of event streams to the data returned by your invocation. In addition, the runtime can be configured to cache the data returned by your method, script or UDF invocations.
			</p>
			<p>
				Joins or outer joins in which only SQL statements or method, script or UDF invocations are listed in the <code class="literal">from</code> clause and no other event streams are termed <span class="emphasis"><em>passive</em></span> joins. A passive join does not produce an insert or remove stream and therefore does not invoke statement listeners with results. A passive join can be iterated on (polled) using a statement's <code class="literal">safeIterator</code> and <code class="literal">iterator</code> methods.
			</p>
			<p>
				The following restrictions currently apply:
			</p>
			<div class="itemizedlist">
				<ul compact="compact">
					<li>
						<p>
							A invocation cannot declare data windows; That is, you cannot create a time or length window on an invocation. Instead, use <code class="literal">insert into</code> to make join results available for further processing.
						</p>
					</li>
				</ul>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="joining_method_syntax"></a>5.14.1. Joining Method, Script or UDF Invocation Results</h3>
						</div>
					</div>
				</div>
				<p>
					The syntax for a method, script or UDF invocation in the <code class="literal">from</code> clause of a statement is:
				</p>
				<pre class="synopsis">method: [<span class="emphasis"><em>class_or_variable_name</em></span>.]<span class="emphasis"><em>method_script_udf_name</em></span>[(<span class="emphasis"><em>parameter_expressions</em></span>)] [@type(<span class="emphasis"><em>eventtype_name</em></span>)]</pre>
				<p>
					The <code class="literal">method</code> keyword denotes a method, script or UDF invocation. It is followed by an optional class or variable name.
					The <span class="emphasis"><em>method_script_udf_name</em></span> is the name of the method, script or user-defined function.
					If you have parameters to your method, script or UDF invocation, these are placed in
					parentheses after the method or script name. Any expression is allowed as a parameter, and individual parameter expressions are separated by a comma.
					Expressions may also use event properties of the joined stream.
				</p>
				<p>
					In case the return type of the method is <code class="literal">EventBean</code> instances, you must provide the <code class="literal">@type</code> annotation to name the event type of events returned.
					Otherwise <code class="literal">@type</code> is not allowed.
				</p>
				<p>
					In the sample join statement shown next, the method <code class="literal">lookupAsset</code> provided by class (or variable) <code class="literal">MyLookupLib</code> returns one or more rows based on the asset id (a property of the <code class="literal">AssetMoveEvent</code>) that is passed to the method:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from AssetMoveEvent, method:MyLookupLib.lookupAsset(assetId)</pre>
				<p>
					The following statement demonstrates the use of the <code class="literal">where</code> clause to join events to the rows returned by an invocation, which in this example does not take parameters:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetId, assetDesc from AssetMoveEvent as asset, 
       method:MyLookupLib.getAssetDescriptions() as desc 
where asset.assetid = desc.assetid</pre>
				<p>
					Your method, scipt or UDF invocation may return zero, one or many rows for each invocation. If you have caching enabled through configuration, then the runtime can avoid the invocation and instead use cached results. Similar to SQL joins, the runtime also indexes cached result rows such that join operations based on the <code class="literal">where</code> clause or outer-join <code class="literal">on</code> clause can be very efficient, especially if your invocation returns a large number of rows.
				</p>
				<p>
					If the time taken by method, script or UDF invocations is critical to your application, you may configure local caches as <a class="xref" href="configuration.html#configuration-common-methodinvocations" title="17.4.11. From-Clause Method Invocation">Section 17.4.11, “From-Clause Method Invocation”</a> describes.
				</p>
				<p>
					The compiler analyzes the expression in the EPL <code class="literal">where</code> clause and outer-join <code class="literal">on</code> clause, if present, and builds the appropriate indexes from that information at runtime, to ensure fast matching of event stream events to invocation results, even if your invocation returns a large number of rows. Your applications must ensure to configure a cache for your invocation using configuration, as such indexes are held with regular data in a cache. If your application does not enable caching of invocation results, the runtime does not build indexes on cached data.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="joining_method_polling"></a>5.14.2. Polling Invocation Results via Iterator</h3>
						</div>
					</div>
				</div>
				<p>
					Usually your invocation will take part in a join and thus be triggered by an event or pattern occurrence. Instead, your application may need to poll an invocation and thus use SQL query execution and caching facilities and obtain event data and metadata.
				</p>
				<p>
					Your statement can specify an invocation in the <code class="literal">from</code> clause without a join. Such a stand-alone invocation does not post new events, and may only be queried via the <code class="literal">iterator</code> poll API. Your statement may still use variables.
				</p>
				<p>
					The next statement assumes that a <code class="literal">category_var</code> variable has been declared. It polls the <code class="literal">getAssetDescriptions</code> method passing the current value of the <code class="literal">category_var</code> EPL variable:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from method:MyLookupLib.getAssetDescriptions(category_var)]</pre>
				<p>
					Use the <code class="literal">iterator</code> and <code class="literal">safeIterator</code> methods on <code class="literal">EPStatement</code> to obtain results. The statement does not post events to listeners, it is strictly passive in that sense.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="joining_method_exposing"></a>5.14.3. Providing the Method</h3>
						</div>
					</div>
				</div>
				<p>
					Your application can provide a public static method or can provide an instance method of an existing object. The declaring class must be public as well.
					The method must accept the same number and type of parameters as listed in the parameter expression list.
				</p>
				<p>
					The examples herein mostly use public static methods. For a detail description of instance methods please see <a class="xref" href="epl_clauses.html#variable_eventtype" title="5.17.5. Class and Event-Type Variables">Section 5.17.5, “Class and Event-Type Variables”</a> and below example.
				</p>
				<p>
					If your invocation returns either no row or only one row, then the return type of the method can be a Java class, <code class="literal">java.util.Map</code> or <code class="literal">Object[]</code> (object-array). If your invocation can return more then one row, then the return type of the method must be an array of Java class, array of <code class="literal">Map</code>, <code class="literal">Object[][]</code> (object-array 2-dimensional) or
					<code class="literal">Collection</code> or <code class="literal">Iterator</code> (or subtypes thereof).
				</p>
				<p>
					If you are using a Java class, an array of Java class or a <code class="literal">Collection&lt;Class&gt;</code> or an <code class="literal">Iterator&lt;Class&gt;</code> as the return type, then the class must adhere to JavaBean conventions: it must expose properties through getter methods.
				</p>
				<p>
					If you are using <code class="literal">java.util.Map</code> or an array of <code class="literal">Map</code> or a <code class="literal">Collection&lt;Map&gt;</code> or an <code class="literal">Iterator&lt;Map&gt;</code> as the return type, please note the following:
				</p>
				<div class="itemizedlist">
					<ul>
						<li>
							Your application must provide a second method that returns event property metadata, as the next section outlines.
						</li>
						<li>
							Each map instance returned by your method should have <code class="literal">String</code>-type keys and object values (<code class="literal">Map&lt;String, Object&gt;</code>).
						</li>
					</ul>
				</div>
				<p>
					If you are using <code class="literal">Object[]</code> (object-array) or <code class="literal">Object[][]</code> (object-array 2-dimensional) or <code class="literal">Collection&lt;Object[]&gt;</code> or <code class="literal">Iterator&lt;Object[]&gt;</code> as the return type, please note the following:
				</p>
				<div class="itemizedlist">
					<ul>
						<li>
							Your application must provide a second method that returns event property metadata, as the next section outlines.
						</li>
						<li>
							Each object-array instance returned by your method should have the exact same array position for values as the property metadata indicates and the array length must be the same as the
							number of properties.
						</li>
					</ul>
				</div>
				<p>
					Your application method must return either of the following:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								A <code class="literal">null</code> value or an empty array to indicate an empty result (no rows).
							</p>
						</li>
						<li>
							<p>
								A Java object or <code class="literal">Map</code> or <code class="literal">Object[]</code> to indicate a zero (null) or one-row result.
							</p>
						</li>
						<li>
							<p>
								Return multiple result rows by returning either:
							</p>
							<div class="itemizedlist">
								<ul>
									<li>
										An array of Java objects.
									</li>
									<li>
										An array of <code class="literal">Map</code> instances.
									</li>
									<li>
										An array of <code class="literal">Object[]</code> instances.
									</li>
									<li>
										An array of <code class="literal">EventBean[]</code> instances (requires <code class="literal">@type</code>).
									</li>
									<li>
										A <code class="literal">Collection</code> of Java objects.
									</li>
									<li>
										A <code class="literal">Collection</code> of <code class="literal">Map</code> instances.
									</li>
									<li>
										A <code class="literal">Collection</code> of <code class="literal">Object[]</code> instances.
									</li>
									<li>
										An <code class="literal">Collection</code> of <code class="literal">EventBean[]</code> instances (requires <code class="literal">@type</code>).
									</li>
									<li>
										An <code class="literal">Iterator</code> of Java objects.
									</li>
									<li>
										An <code class="literal">Iterator</code> of <code class="literal">Map</code> instances.
									</li>
									<li>
										An <code class="literal">Iterator</code> of <code class="literal">Object[]</code> instances.
									</li>
									<li>
										An <code class="literal">Iterator</code> of <code class="literal">EventBean[]</code> instances (requires <code class="literal">@type</code>).
									</li>
								</ul>
							</div>
						</li>
					</ol>
				</div>
				<p>
					As an example, consider the method 'getAssetDescriptions' provided by class 'MyLookupLib' as discussed earlier:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetId, assetDesc from AssetMoveEvent as asset,
       method:com.mypackage.MyLookupLib.getAssetDescriptions() as desc 
  where asset.assetid = desc.assetid</pre>
				<p>
					The 'getAssetDescriptions' method may return multiple rows and is therefore declared to return an array of the class 'AssetDesc'. The class AssetDesc is a POJO class (not shown here):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class MyLookupLib {
  ...
  public static AssetDesc[] getAssetDescriptions() {
    ...
    return new AssetDesc[] {...};
  }</pre>
				<p>
					The example above specifies the full Java class name of the class 'MyLookupLib' class in the statement. The package name does not need to be part of the EPL if your application imports the package using the auto-import configuration through the API or XML, as outlined in <a class="xref" href="configuration.html#configuration-common-imports" title="17.4.2. Class and Package Imports">Section 17.4.2, “Class and Package Imports”</a>.
				</p>
				<p>
					Alternatively the example above could return a <code class="literal">Collection</code> wherein the method declares as <code class="literal">public static Collection&lt;AssetDesc&gt; getAssetDescriptions() {...}</code> or an <code class="literal">Iterator</code> wherein the method declares as <code class="literal">public static Iterator&lt;AssetDesc&gt; getAssetDescriptions() {...}</code>.
				</p>
				<p>
					Method overloading is allowed as long as overloaded methods return the same result type.
				</p>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="joining_method_exposing_instance"></a>5.14.3.1. Providing an Instance Method</h4>
							</div>
						</div>
					</div>
					<p>
						If your application has an existing object instance such as a service or a dependency injected bean then it must make the instance available as a variable. Please see <a class="xref" href="epl_clauses.html#variable_eventtype" title="5.17.5. Class and Event-Type Variables">Section 5.17.5, “Class and Event-Type Variables”</a>
						for more information.
					</p>
					<p>
						For example, assuming you provided a <code class="literal">stateChecker</code> variable that points to an object instance that provides a public <code class="literal">getMatchingAssets</code> instance method
						and that returns property <code class="literal">assetIds</code>, you may use the state checker service in the <code class="literal">from</code>-clause as follows:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetIds from AssetMoveEvent, method:stateChecker.getMatchingAssets(assetDesc)</pre>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="joining_method_map"></a>5.14.4. Using a <code class="literal">Map</code> Return Type</h3>
						</div>
					</div>
				</div>
				<p>
					Your application may return <code class="literal">java.util.Map</code> or an array of <code class="literal">Map</code> from invocations. If doing so, your application must provide metadata about each row: it must declare the property name and property type of each <code class="literal">Map</code> entry of a row. This information allows the compiler to perform type checking of expressions used within the statement.
				</p>
				<p>
					You declare the property names and types of each row by providing a method that returns property metadata. The metadata method must follow these conventions:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								The method name providing the property metadata must have same method name appended by the literal <code class="literal">Metadata</code>.
							</p>
						</li>
						<li>
							<p>
								The method must have an empty parameter list and must be declared public and static.
							</p>
						</li>
						<li>
							<p>
								The method providing the metadata must return a <code class="literal">Map</code> of <code class="literal">String</code> property name keys and <code class="literal">java.lang.Class</code> property name types (<code class="literal">Map&lt;String, Class&gt;</code>).
							</p>
						</li>
					</ol>
				</div>
				<p>
					In the following example, a class 'MyLookupLib' provides a method to return historical data based on asset id and asset code:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetId, location, x_coord, y_coord from AssetMoveEvent as asset,
       method:com.mypackage.MyLookupLib.getAssetHistory(assetId, assetCode) as history</pre>
				<p>
					A sample implementation of the class 'MyLookupLib' is shown below.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class MyLookupLib {
  ...
  // For each column in a row, provide the property name and type
  //
  public static Map&lt;String, Class&gt; getAssetHistoryMetadata() {
    Map&lt;String, Class&gt; propertyNames = new HashMap&lt;String, Class&gt;();
    propertyNames.put("location", String.class);
    propertyNames.put("x_coord", Integer.class);
    propertyNames.put("y_coord", Integer.class);
    return propertyNames;
  }
... 
  // Lookup rows based on assetId and assetCode
  // 
  public static Map&lt;String, Object&gt;[] getAssetHistory(String assetId, String assetCode) {
    Map rows = new Map[2];	// this sample returns 2 rows
    for (int i = 0; i &lt; 2; i++) {
      rows[i] = new HashMap();
      rows[i].put("location", "somevalue");
      rows[i].put("x_coord", 100);
      // ... set more values for each row
    }
    return rows;
  }</pre>
				<p>
					In the example above, the 'getAssetHistoryMetadata' method provides the property metadata: the names and types of properties in each row. The compiler calls this method once per statement to determine event typing information.
				</p>
				<p>
					The 'getAssetHistory' method returns an array of <code class="literal">Map</code> objects that are two rows. The implementation shown above is a simple example. The parameters to the method are the assetId and assetCode properties of the AssetMoveEvent joined to the method. The runtime calls this method for each insert and remove stream event in AssetMoveEvent.
				</p>
				<p>
					To indicate that no rows are found in a join, your application method may return either a <code class="literal">null</code> value or an array of size zero.
				</p>
				<p>
					Alternatively the example above could return a <code class="literal">Collection</code> wherein the method declares as <code class="literal">public static Collection&lt;Map&gt; getAssetHistory() {...}</code> or an <code class="literal">Iterator</code> wherein the method declares as <code class="literal">public static Iterator&lt;Map&gt; getAssetHistory() {...}</code>.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="joining_method_oa"></a>5.14.5. Using a Object Array Return Type</h3>
						</div>
					</div>
				</div>
				<p>
					Your application may return <code class="literal">Object[]</code> (object-array) or an array of <code class="literal">Object[]</code> (object-array 2-dimensional) from invocations. If doing so, your application must provide metadata about each row: it must declare the property name and property type of each array entry of a row in the exact same order as provided by value rows. This information allows the runtime to perform type checking of expressions used within the statement.
				</p>
				<p>
					You declare the property names and types of each row by providing a method that returns property metadata. The metadata method must follow these conventions:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								The method name providing the property metadata must have same method name appended by the literal <code class="literal">Metadata</code>.
							</p>
						</li>
						<li>
							<p>
								The method must have an empty parameter list and must be declared public and static.
							</p>
						</li>
						<li>
							<p>
								The method providing the metadata must return a <code class="literal">LinkedHashMap</code> of <code class="literal">String</code> property name keys and <code class="literal">java.lang.Class</code> property name types (<code class="literal">Map&lt;String, Class&gt;</code>).
							</p>
						</li>
					</ol>
				</div>
				<p>
					In the following example, a class 'MyLookupLib' provides a method to return historical data based on asset id and asset code:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select assetId, location, x_coord, y_coord from AssetMoveEvent as asset,
       method:com.mypackage.MyLookupLib.getAssetHistory(assetId, assetCode) as history</pre>
				<p>
					A sample implementation of the class 'MyLookupLib' is shown below.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class MyLookupLib {
  ...
  // For each column in a row, provide the property name and type
  //
  public static LinkedHashMap&lt;String, Class&gt; getAssetHistoryMetadata() {
    LinkedHashMap&lt;String, Class&gt; propertyNames = new LinkedHashMap&lt;String, Class&gt;();
    propertyNames.put("location", String.class);
    propertyNames.put("x_coord", Integer.class);
    propertyNames.put("y_coord", Integer.class);
    return propertyNames;
  }
... 
  // Lookup rows based on assetId and assetCode
  // 
  public static Object[][] getAssetHistory(String assetId, String assetCode) {
    Object[][] rows = new Object[5][];	// this sample returns 5 rows
    for (int i = 0; i &lt; 5; i++) {
      rows[i] = new Object[2]; // single row has 2 fields
      rows[i][0]  = "somevalue";
      rows[i][1] = 100;
      // ... set more values for each row
    }
    return rows;
  }</pre>
				<p>
					In the example above, the 'getAssetHistoryMetadata' method provides the property metadata: the names and types of properties in each row. The compiler calls this method once per statement to determine event typing information.
				</p>
				<p>
					The 'getAssetHistory' method returns an <code class="literal">Object[][]</code> that represents five rows. The implementation shown above is a simple example. The parameters to the method are the assetId and assetCode properties of the AssetMoveEvent joined to the method. The runtime calls this method for each insert and remove stream event in AssetMoveEvent.
				</p>
				<p>
					To indicate that no rows are found in a join, your application method may return either a <code class="literal">null</code> value or an array of size zero.
				</p>
				<p>
					Alternatively the example above could return a <code class="literal">Collection</code> wherein the method declares as <code class="literal">public static Collection&lt;Object[]&gt; getAssetHistory() {...}</code> or an <code class="literal">Iterator</code> wherein the method declares as <code class="literal">public static Iterator&lt;Object[]&gt; getAssetHistory() {...}</code>.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="joining_method_eventbeanarray"></a>5.14.6. Using an <code class="literal">EventBean</code> Return Type</h3>
						</div>
					</div>
				</div>
				<p>
					When the return type is <code class="literal">EventBean[]</code>, <code class="literal">Collection&lt;EventBean&gt;</code> or <code class="literal">Iterator&lt;EventBean&gt;</code>, you must specify the event type name using <code class="literal">@type</code>.
				</p>
				<p>
					For example assuming the event type <code class="literal">ItemEvent</code> is declared as <code class="literal">create schema ItemEvent(p0 string)</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MyEvent, method:MyLib.myFunc() @type(ItemEvent)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public static EventBean[] myFunc(EPLMethodInvocationContext context) {
  EventBean[1] events = new EventBean[1];
  events[0] = context.getEventBeanService().adapterForMap(Collections.singletonMap("p0", "hello"), "ItemEvent");
  return events;
}</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="joining_method_script"></a>5.14.7. Providing the Script</h3>
						</div>
					</div>
				</div>
				<p>
					Your script must declare the return type as <code class="literal">EventBean[]</code>. In the <code class="literal">@type</code> annotation you must provide an event type name.
				</p>
				<p>
					For example assuming the event type <code class="literal">ItemEvent</code> is declared as <code class="literal">create schema ItemEvent(id string)</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select id from MyEvent, method:myItemProducerScript()</pre>
				<p>
					The example JavaScript script is:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create expression EventBean[] @type(ItemEvent) js:myItemProducerScript() [
myItemProducerScript()
function myItemProducerScript() {
  var EventBeanArray = Java.type(\"com.espertech.esper.common.client.EventBean[]\");
  var events = new EventBeanArray(1);
  events[0] = epl.getEventBeanService().adapterForMap(java.util.Collections.singletonMap(\"id\", \"id1\"), \"ItemEvent\");
  return events;
}]</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="joining_method_udf"></a>5.14.8. Providing the UDF</h3>
						</div>
					</div>
				</div>
				<p>
					Your script must declare the return type of the UDF as <code class="literal">EventBean[]</code>. In the <code class="literal">@type</code> annotation you must provide an event type name.
				</p>
				<p>
					For example assuming you have registered a user-defined function <code class="literal">myUserDefinedFunction</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select id from MyEvent, method:myUserDefinedFunction() @type(ItemEvent)</pre>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl_createschema"></a>5.15. Declaring an Event Type: <span class="emphasis"><em>Create Schema</em></span></h2>
					</div>
				</div>
			</div><a id="d0e13674" class="indexterm"></a><a id="d0e13677" class="indexterm"></a>
			<p>
				EPL allows declaring an event type via the <code class="literal">create schema</code> clause and also by configuring predefined types. The term schema and event type has the same meaning in EPL.
			</p>
			<p>
				When using the <code class="literal">create schema</code> syntax to declare an event type, the runtime automatically removes the event type on undeploy.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl_createschema_properties"></a>5.15.1. Declare an Event Type by Providing Names and Types</h3>
						</div>
					</div>
				</div>
				<p>
					The synopsis of the <code class="literal">create schema</code> syntax providing property names and types is:
				</p>
				<pre class="synopsis">create [map | objectarray | json | avro | xml] schema <span class="emphasis"><em>schema_name</em></span> [as] 
    (<span class="emphasis"><em>property_name</em></span> <span class="emphasis"><em>property_type</em></span> [,<span class="emphasis"><em>property_name</em></span> <span class="emphasis"><em>property_type</em></span> [,...])
  [inherits <span class="emphasis"><em>inherited_event_type</em></span>[, <span class="emphasis"><em>inherited_event_type</em></span>] [,...]]
  [starttimestamp <span class="emphasis"><em>timestamp_property_name</em></span>]
  [endtimestamp <span class="emphasis"><em>timestamp_property_name</em></span>]
  [copyfrom <span class="emphasis"><em>copy_type_name</em></span> [, <span class="emphasis"><em>copy_type_name</em></span>] [,...]]</pre>
				<p>
					The <code class="literal">create</code> keyword can be followed by <code class="literal">map</code> to instruct the compiler to represent events of that type by the Map event representation, or <code class="literal">objectarray</code> to denote an Object-array event type, or <code class="literal">json</code> to denote a JSON event type, or <code class="literal">avro</code> to denote an Avro event type, or <code class="literal">xml</code> to denote an XML event type. If neither the <code class="literal">map</code> or <code class="literal">objectarray</code> or <code class="literal">json</code> or <code class="literal">avro</code> or <code class="literal">xml</code> keywords are provided, the compiler default event representation applies.
				</p>
				<p>
					After <code class="literal">create schema</code> follows a <span class="emphasis"><em>schema_name</em></span>. The schema name is the event type name.
				</p>
				<p>
					The <span class="emphasis"><em>property_name</em></span> is an identifier providing the event property name. The <span class="emphasis"><em>property_type</em></span> is also required for each property. Valid property types are listed in <a class="xref" href="epl_clauses.html#variable_create" title="5.17.1. Creating Variables: The Create Variable Clause">Section 5.17.1, “Creating Variables: The Create Variable Clause”</a>
					and in addition include:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Any Java class name, fully-qualified or the simple class name if imports are configured. Parameterized types such as <code class="literal">java.util.Collection&lt;String&gt;</code> are supported as well.
							</p>
						</li>
						<li>
							<p>
								Add left and right square brackets <code class="literal">[]</code> to any type to denote an array-type event property, and <code class="literal">[][]</code> for two-dimensional arrays.
							</p>
						</li>
						<li>
							<p>
								Use an event type name as a property type.
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">null</code> keyword for a null-typed property.
							</p>
						</li>
					</ol>
				</div>
				<p>
					For XML event types please check <a class="xref" href="appendix_eventrepxml.html#appendix_eventrepxml_createschema" title="I.5. Using XML-Schema Annotations with create xml schema">Section I.5, “Using XML-Schema Annotations with create xml schema”</a> for information on how to declare properties.
				</p>
				<p>
					The optional <code class="literal">inherits</code> keywords is followed by a comma-separated list of event type names that are the supertypes to the declared type.
				</p>
				<p>
					The optional <code class="literal">starttimestamp</code> keyword is followed by a property name. Use this to tell the compiler that your event has a timestamp. The compiler checks that the property name exists on the declared type and returns a date-time value.
					Declare a timestamp property if you want your events to implicitly carry a timestamp value for convenient use with interval algebra methods as a start timestamp.
				</p>
				<p>
					The optional <code class="literal">endtimestamp</code> keyword is followed by a property name. Use this together with starttimestamp to tell the compiler that your event has a duration. The compiler checks that the property name exists on the declared type and returns a date-time value.
					Declare an endtimestamp property if you want your events to implicitly carry a duration value for convenient use with interval algebra methods.
				</p>
				<p>
					The optional <code class="literal">copyfrom</code> keyword is followed by a comma-separate list of event type names. For each event type listed, the compiler looks up that type and adds all event property definitions to the newly-defined type, in addition to those listed explicitly (if any). The resulting order of properties is that copied-from properties are first (in the order of event types and their property order) and explicitly-listed properties last.
				</p>
				<p>
					A few example event type declarations follow:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Declare type SecurityEvent
create schema SecurityEvent as (ipAddress string, userId String, numAttempts int)
			
// Declare type AuthorizationEvent with the roles property being an array of String 
// and the hostinfo property being a POJO object
create schema AuthorizationEvent(group String, roles String[], hostinfo com.mycompany.HostNameInfo)

// Declare type CompositeEvent in which the innerEvents property is an array of SecurityEvent
create schema CompositeEvent(group String, innerEvents SecurityEvent[])

// Declare type WebPageVisitEvent that inherits all properties from PageHitEvent
create schema WebPageVisitEvent(userId String) inherits PageHitEvent

// Declare a type with start and end timestamp (i.e. event with duration).
create schema RoboticArmMovement (robotId string, startts long, endts long) 
  starttimestamp startts endtimestamp endts
  
// Create a type that has all properties of SecurityEvent plus a userName property
create schema ExtendedSecurityEvent (userName string) copyfrom SecurityEvent

// Create a type that has all properties of SecurityEvent 
create schema SimilarSecurityEvent () copyfrom SecurityEvent

// Create a type that has all properties of SecurityEvent and WebPageVisitEvent plus a userName property
create schema WebSecurityEvent (userName string) copyfrom SecurityEvent, WebPageVisitEvent</pre>
				<p>
					To elaborate on the <code class="literal">inherits</code> keyword, consider the following two schema definitions:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema Foo as (prop1 string)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema Bar() inherits Foo</pre>
				<p>
					Following above schema, Foo is a supertype or Bar and therefore any Bar event also fulfills Foo and matches where Foo matches. A statement such as <code class="literal">select * from Foo</code>
					returns any Foo event as well as any event that is a subtype of Foo such as all Bar events. When your statements don't use any Foo events there is no cost, thus <code class="literal">inherits</code> is
					generally an effective way to share properties between types. The start and end timestamp are also inherited from any supertype that has the timestamp property names defined.
				</p>
				<p>
					The optional <code class="literal">copyfrom</code> keyword is for defining a schema based on another schema. This keyword causes the compiler to copy property definitions: There is no inherits, extends, supertype or subtype relationship between the types listed.
				</p>
				<p>
					To define an event type <code class="literal">Bar</code> that has the same properties as <code class="literal">Foo</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema Foo as (prop1 string)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema Bar() copyfrom Foo</pre>
				<p>
					To define an event type <code class="literal">Bar</code> that has the same properties as <code class="literal">Foo</code> and that adds its own property <code class="literal">prop2</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema Foo as (prop1 string)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema Bar(prop2 string) copyfrom Foo</pre>
				<p>
					If neither the <code class="literal">map</code> or <code class="literal">objectarray</code> or <code class="literal">json</code> or <code class="literal">avro</code> keywords are provided, the following rule applies:
				</p>
				<div class="itemizedlist">
					<ul>
						<li>
							<p>If the create-schema statement provides the <code class="literal">@EventRepresentation(objectarray)</code> annotation the runtime expects object array events.</p>
						</li>
						<li>
							<p>If the statement provides the <code class="literal">@EventRepresentation(json)</code> annotation the runtime expects JSON strings as events.</p>
						</li>
						<li>
							<p>If the statement provides the <code class="literal">@EventRepresentation(avro)</code> annotation the runtime expects Avro objects as events.</p>
						</li>
						<li>
							<p>If the statement provides the <code class="literal">@EventRepresentation(map)</code> annotation the runtime expects Map objects as events.</p>
						</li>
						<li>
							<p>If neither annotation is provided, the runtime uses the configured default event representation as discussed in <a class="xref" href="configuration.html#configuration-common-eventmeta-representation" title="17.4.9.1. Default Event Representation">Section 17.4.9.1, “Default Event Representation”</a>.</p>
						</li>
					</ul>
				</div>
				<p>
					The following two statements both instructs the compiler to represent Foo events as object arrays. When sending Foo events into the runtime use the <code class="literal">sendEventObjectArray(Object[] data, String typeName)</code> footprint.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create objectarray schema Foo as (prop1 string)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@EventRepresentation(objectarray) create schema Foo as (prop1 string)</pre>
				<p>
					The next two statements both instructs the compiler to represent Foo events as Maps. When sending Foo events into the runtime use the <code class="literal">sendEventMap(Map data, String typeName)</code> footprint.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create map schema Foo as (prop1 string)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@EventRepresentation(map) create schema Foo as (prop1 string)</pre>
				<p>
					The following two statements both instructs the compiler to represent Foo events as JSON. When sending Foo events into the runtime use the <code class="literal">sendEventJson(String json, String typeName)</code> footprint.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create json schema Foo as (prop1 string)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@EventRepresentation(json) create schema Foo as (prop1 string)</pre>
				<p>
					The following two statements both instructs the compiler to represent Foo events as Avro <code class="literal">GenericData.Record</code>. When sending Foo events into the runtime use the <code class="literal">sendEventAvro(Object genericDataDotRecord, String typeName)</code> footprint.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create avro schema Foo as (prop1 string)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@EventRepresentation(avro) create schema Foo as (prop1 string)</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl_createschema_class"></a>5.15.2. Declare an Event Type by Providing a Class Name</h3>
						</div>
					</div>
				</div>
				<p>
					When using Java classes as the underlying event representation your application may simply provide the class name:
				</p>
				<pre class="synopsis">create schema <span class="emphasis"><em>schema_name</em></span> [as] <span class="emphasis"><em>class_name</em></span>
  [starttimestamp <span class="emphasis"><em>timestamp_property_name</em></span>]
  [endtimestamp <span class="emphasis"><em>timestamp_property_name</em></span>]</pre>
				<p>
					The <span class="emphasis"><em>class_name</em></span> must be a fully-qualified class name (including the package name) if imports are not configured. If your application configures imports then the simple class name suffices without package name.
					Parameterized types such as <code class="literal">java.util.MyEvent&lt;String&gt;</code> are supported as well.
				</p>
				<p>
					The optional <code class="literal">starttimestamp</code> and <code class="literal">endtimestamp</code> keywords have a meaning as defined earlier.
				</p>
				<p>
					The next example statements declare an event type based on a class:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Shows the use of a fully-qualified class name to declare the LoginEvent event type
create schema LoginEvent as com.mycompany.LoginValue

// When the configuration includes imports, the declaration does not need a package name
create schema LogoutEvent as SignoffValue</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl_createschema_variant"></a>5.15.3. Declare a Variant Stream</h3>
						</div>
					</div>
				</div>
				<p>
					A variant stream is a predefined stream into which events of multiple disparate event types can be inserted.
					Please see <a class="xref" href="epl_clauses.html#insert-into-merging-types" title="5.10.3. Merging Disparate Types of Events: Variant Streams">Section 5.10.3, “Merging Disparate Types of Events: Variant Streams”</a> for rules regarding property visibility and additional information.
				</p>
				<p>
					The synopsis is:
				</p>
				<pre class="synopsis">create variant schema <span class="emphasis"><em>schema_name</em></span> [as] <span class="emphasis"><em>eventtype_name|*</em></span> [, <span class="emphasis"><em>eventtype_name|*</em></span>] [,...]</pre>
				<p>
					Provide the <code class="literal">variant</code> keyword to declare a variant stream.
				</p>
				<p>
					The '<code class="literal">*</code>' wildcard character declares a variant stream that accepts any type of event inserted into the variant stream.
				</p>
				<p>
					Provide <span class="emphasis"><em>eventtype_name</em></span> if the variant stream should hold events of the given type only. When using <code class="literal">insert into</code> to
					insert into the variant stream the compiler checks to ensure the inserted event type or its supertypes match the required event type.
				</p>
				<p>
					A few examples are shown below:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Create a variant stream that accepts only LoginEvent and LogoutEvent event types
create variant schema SecurityVariant as LoginEvent, LogoutEvent

// Create a variant stream that accepts any event type
create variant schema AnyEvent as *</pre>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="split_overview"></a>5.16. Splitting and Duplicating Streams</h2>
					</div>
				</div>
			</div>
			<p>
				EPL offers a convenient syntax to splitting, routing or duplicating events into multiple streams, and for receiving unmatched events among a set of filter criteria.
			</p>
			<p>
				For splitting a single event that acts as a container and expose child events as a property of itself consider the contained-event syntax as described in <a class="xref" href="epl_clauses.html#epl-containedeventselect" title="5.19. Contained-Event Selection">Section 5.19, “Contained-Event Selection”</a>.
				For generating marker events for contained-events please see below.
			</p>
			<p>
				You may define a triggering event or pattern in the <code class="literal">on</code>-part of the statement followed by multiple <code class="literal">insert into</code>, <code class="literal">select</code> and <code class="literal">where</code> clauses.
			</p>
			<p>
				The synopsis is:
			</p>
			<pre class="synopsis">[context <span class="emphasis"><em>context_name</em></span>]
on <span class="emphasis"><em>event_type</em></span>[(<span class="emphasis"><em>filter_criteria</em></span>)] [as <span class="emphasis"><em>stream_name</em></span>]
insert into <span class="emphasis"><em>insert_into_def</em></span> select <span class="emphasis"><em>select_list</em></span> [where <span class="emphasis"><em>condition</em></span>]
[insert into <span class="emphasis"><em>insert_into_def</em></span> select <span class="emphasis"><em>select_list</em></span> [from <span class="emphasis"><em>contained-event-selection</em></span>] [where <span class="emphasis"><em>condition</em></span>]]
[insert into <span class="emphasis"><em>insert_into_def</em></span> select <span class="emphasis"><em>select_list</em></span> [from <span class="emphasis"><em>contained-event-selection</em></span>] [where <span class="emphasis"><em>condition</em></span>]]
[insert into...]
[output first | all]</pre>
			<p>
				The <span class="emphasis"><em>event_type</em></span> is the name of the type of events that trigger the split stream. It is optionally
				followed by <span class="emphasis"><em>filter_criteria</em></span> which are filter expressions to apply to arriving events. The optional <code class="literal">as</code> keyword
				can be used to assign a stream name. Patterns and named windows can also be specified in the <code class="literal">on</code> clause.
			</p>
			<p>
				Following the <code class="literal">on</code>-clause is one or more <span class="emphasis"><em>insert into</em></span> clauses as described in <a class="xref" href="epl_clauses.html#epl-insert-into" title="5.10. Merging Streams and Continuous Insertion: The Insert Into Clause">Section 5.10, “Merging Streams and Continuous Insertion: The Insert Into Clause”</a> and <span class="emphasis"><em>select</em></span> clauses as described in <a class="xref" href="epl_clauses.html#epl-select-list" title="5.3. Choosing Event Properties and Events: The Select Clause">Section 5.3, “Choosing Event Properties and Events: The Select Clause”</a>.
			</p>
			<p>
				The second and subsequent <code class="literal">insert into</code> and <code class="literal">select</code> clause pair can have a <code class="literal">from</code> clause for <span class="emphasis"><em>contained-event-selection</em></span>.
				This is useful when your trigger events themselves contain events that must be processed individually and that may be delimited by marker events that you can define.
			</p>
			<p>
				Each <code class="literal">select</code> clause may be followed by a <code class="literal">where</code> clause containing a condition. If the condition is true for the event, the runtime transforms the event according to the <code class="literal">select</code> clause and inserts it into the corresponding stream.
			</p>
			<p>
				At the end of the statement can be an optional <code class="literal">output</code> clause. By default the runtime inserts into the first stream for which the <code class="literal">where</code> clause condition matches if one was specified, starting from the top. If you specify the <code class="literal">output all</code> keywords, then the runtime inserts into each stream (not only the first stream) for which the <code class="literal">where</code> clause condition matches or that do not have a <code class="literal">where</code> clause.
			</p>
			<p>
				If, for a given event, none of the <code class="literal">where</code> clause conditions match, the statement listener receives the unmatched event. The statement listener only receives unmatched events and does not receive any transformed or inserted events. The <code class="literal">iterator</code> method to the statement returns no events.
			</p>
			<p>
				You may specify an optional context name to the effect that the split-stream operates according to the context dimensional information as declared for the context. See <a class="xref" href="context.html" title="Chapter 4. Context and Context Partitions">Chapter 4, <i>Context and Context Partitions</i></a> for more information.
			</p>
			<p>
				In the below sample statement, the runtime inserts each <code class="literal">OrderEvent</code> into the <code class="literal">LargeOrders</code> stream if the order quantity is 100 or larger, or into the <code class="literal">SmallOrders</code> stream if the order quantity is smaller then 100:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on OrderEvent 
  insert into LargeOrders select * where orderQty &gt;= 100
  insert into SmallOrders select *</pre>
			<p>
				The next example statement adds a new stream for medium-sized orders. The new stream receives orders that have an order quantity between 20 and 100:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on OrderEvent 
  insert into LargeOrders select orderId, customer where orderQty &gt;= 100
  insert into MediumOrders select orderId, customer where orderQty between 20 and 100
  insert into SmallOrders select orderId, customer where orderQty &gt; 0</pre>
			<p>
				As you may have noticed in the above statement, orders that have an order quantity of zero don't match any of the conditions. The runtime does not insert such order events into any stream and the listener to the statement receives these unmatched events.
			</p>
			<p>
				By default the runtime inserts into the first <code class="literal">insert into</code> stream without a <code class="literal">where</code> clause or for which the <code class="literal">where</code> clause condition matches. To change the default behavior and insert into all matching streams instead (including those without a <code class="literal">where</code> clause), add the <code class="literal">output all</code> keywords.
			</p>
			<p>
				The sample statement below shows the use of the <code class="literal">output all</code> keywords. The statement populates both the <code class="literal">LargeOrders</code> stream with large orders as well as the <code class="literal">VIPCustomerOrders</code> stream with orders for certain customers based on customer id:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on OrderEvent 
  insert into LargeOrders select * where orderQty &gt;= 100
  insert into VIPCustomerOrders select * where customerId in (1001, 1002)
  output all</pre>
			<p>
				Since the <code class="literal">output all</code> keywords are present, the above statement inserts each order event into either both streams or only one stream or none of the streams, depending on order quantity and customer id of the order event. The statement delivers order events not inserted into any of the streams to the listeners and/or subscriber to the statement.
			</p>
			<p>
				The following limitations apply to split-stream statements:
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
				<ol>
					<li>
						<p>
							Aggregation functions and the <code class="literal">prev</code> and <code class="literal">prior</code> operators are not available in conditions and the <code class="literal">select</code>-clause.
						</p>
					</li>
				</ol>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="split_containedeventselect"></a>5.16.1. Generating Marker Events for Contained Events</h3>
						</div>
					</div>
				</div>
				<p>
					When a trigger event contains properties that are themselves events, or more generally when your application needs to split the trigger event into multiple events,
					or to generate marker events (begin, end etc.) or process contained events in a defined order, you may specify a <code class="literal">from</code> clause.
				</p>
				<p>
					The <code class="literal">from</code> clause is only allowed for the second and subsequent <code class="literal">insert into</code> and <code class="literal">select</code> clause pair.
					It specifies how the trigger event should get unpacked into individual events and is based on the
					<a class="xref" href="epl_clauses.html#epl-containedeventselect" title="5.19. Contained-Event Selection">Section 5.19, “Contained-Event Selection”</a>.
				</p>
				<p>
					For example, assume there is an order event that contains order items:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema OrderItem(itemId string)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema OrderEvent(orderId string, items OrderItem[])</pre>
				<p>
					We can tell the runtime that, for each order event, it should process in the following order:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>Process a single <code class="literal">OrderBeginEvent</code> that holds just the order id.</p>
						</li>
						<li>
							<p>Process all order items contained in an order event.</p>
						</li>
						<li>
							<p>Process a single <code class="literal">OrderEndEvent</code> that holds just the order id.</p>
						</li>
					</ol>
				</div>
				<p>
					The EPL is:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on OrderEvent
  insert into OrderBeginEvent select orderId
  insert into OrderItemEvent select * from [select orderId, * from items]
  insert into OrderEndEvent select orderId
  output all</pre>
				<p>
					When an <code class="literal">OrderEvent</code> comes in, the runtime first processes an <code class="literal">OrderBeginEvent</code>. The runtime unpacks the order event and for each
					order item processes an <code class="literal">OrderItemEvent</code> containing the respective item. The runtime last processes an <code class="literal">OrderEndEvent</code>.
				</p>
				<p>
					Such begin and end marker events are useful to initiate and terminate an analysis using context declaration, for example.
					The next two statements declare a context and perform a simple count of order items per order:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create context OrderContext 
  initiated by OrderBeginEvent as obe
  terminated by OrderEndEvent(orderId = obe.orderId)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">context OrderContext select count(*) as orderItemCount from OrderItemEvent output when terminated</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="split_atdrop"></a>5.16.2. Splitting Streams with @Priority and @Drop</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">@priority</code> annotation and the <code class="literal">@drop</code> annotation can split streams. Note that annotations require setting prioritized execution in the runtime configuration.
				</p>
				<p>
					For example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into AllOrders select * from OrderEvent;
@priority(1) @drop insert into LargeOrders select * from AllOrders(orderQty &gt; 100);
insert into SmallOrders select * from AllOrders;</pre>
				<p>
					The first statement inserts all <code class="literal">OrderEvent</code> events into the <code class="literal">AllOrders</code> stream. The runtime processes the second statement before it processes the third statement
					since the second statement has <code class="literal">@priority(1)</code>. For the second statement, if the order quantity is greater than 100, the runtime inserts the event into the
					<code class="literal">LargeOrders</code> stream and the runtime stop processing that <code class="literal">AllOrders</code> event since the second statement also has the <code class="literal">@drop</code> annotation.
					If the order quantity is 100 or less, the runtime processes the third statement and inserts the event into the <code class="literal">SmallOrders</code> stream.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="variables_overview"></a>5.17. Variables and Constants</h2>
					</div>
				</div>
			</div><a id="d0e14388" class="indexterm"></a><a id="d0e14391" class="indexterm"></a>
			<p>
				A <span class="emphasis"><em>variable</em></span> is a scalar, object, event or set of aggregation values that is available for use in all statements including patterns. Variables can be used in an expression anywhere in a statement as well as in the <code class="literal">output</code> clause for output rate limiting.
			</p>
			<p>
				Variables must first be declared or configured before use, by defining each variable's type and name. Variables can be created via the <code class="literal">create variable</code> syntax or declared by runtime or static configuration. Variables can be assigned new values by using the <code class="literal">on set</code> syntax or via the <code class="literal">setVariableValue</code> methods on <code class="literal">EPVariableService</code>. The <code class="literal">EPVariableService</code> also provides method to read variable values.
			</p>
			<p>
				A variable can be declared constant. A constant variable always has the initial value and cannot be assigned a new value. A constant variable can be used like any other variable and can be used wherever a constant is required. By declaring a variable constant you enable the runtime to
				optimize and perform query planning knowing that the variable value cannot change.
			</p>
			<p>
				When declaring a class-typed, event-typed or aggregation-typed variable you may read or set individual properties within the same variable.
			</p>
			<p>
				The runtime guarantees consistency and atomicity of variable reads and writes on the level of context partition (this is a soft guarantee, see below). Variables are optimized for fast read access and are also multithread-safe.
			</p>
			<p>
				When you associate a context to the variable then each context partition maintains its own variable value. See <a class="xref" href="context.html#context_variables" title="4.9. Context and Variables">Section 4.9, “Context and Variables”</a> for more information.
			</p>
			<p>
				Your application can only undeploy the statement that created the variable after all statements using the variables are also undeployed.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="variable_create"></a>5.17.1. Creating Variables: The <code class="literal">Create Variable</code> Clause</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">create variable</code> syntax creates a new variable by defining the variable type and name. In alternative to the syntax, variables can also be declared in the configuration object.
				</p>
				<p>
					The synopsis for creating a variable is as follows:
				</p>
				<pre class="synopsis">create [constant] variable <span class="emphasis"><em>variable_type</em></span> [[]] <span class="emphasis"><em>variable_name</em></span> [ = <span class="emphasis"><em>assignment_expression</em></span> ]</pre>
				<p>
					Specify the optional <code class="literal">constant</code> keyword when the variable is a constant whose associated value cannot be altered. Your EPL design should prefer constant variables over non-constant variables.
				</p>
				<p>
					The <span class="emphasis"><em>variable_type</em></span> can be any of the following:
				</p>
				<pre class="synopsis">variable_type
	:  string
	|  char 
	|  character
	|  bool 
	|  boolean
	|  byte
	|  short 
	|  int 
	|  integer 
	|  long 
	|  double
	|  float
	|  object
	|  <span class="emphasis"><em>enum_class</em></span>
	|  <span class="emphasis"><em>class_name</em></span>
	|  <span class="emphasis"><em>event_type_name</em></span></pre>
				<p>
					Variable types can accept null values. The <code class="literal">object</code> type is for an untyped variable that can be assigned any value. You can provide a class name (use imports) or a fully-qualified class name to declare a variable of that Java class type including an enumeration class. You can also supply the name of an event type to declare a variable that holds an event of that type. Parameterized types such as <code class="literal">java.util.Collection&lt;String&gt;</code> are supported as well.
				</p>
				<p>
					Append <code class="literal">[]</code> to the variable type to declare an array variable. A limitation is that if your variable type is an event type then array is not allowed (applies to variables only and not to named windows or tables). For arrays of primitives, specify <code class="literal">[primitive]</code>, for example <code class="literal">int[primitive]</code>.
				</p>
				<p>
					The <span class="emphasis"><em>variable_name</em></span> is an identifier that names the variable. The variable name should not already be in use by another variable.
				</p>
				<p>
					The <code class="literal">assignment_expression</code> is optional. Without an assignment expression the initial value for the variable is <code class="literal">null</code>. If present, it supplies the initial value for the variable.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						When specifying a <span class="emphasis"><em>class_name</em></span> or <span class="emphasis"><em>enum_class</em></span> class name the class must have <code class="literal">public</code> visibility.
					</p>
				</div>
				<p>
					The <code class="literal">EPStatement</code> object of the <code class="literal">create variable</code> statement provides access to variable values.
					The pull API methods <code class="literal">iterator</code> and <code class="literal">safeIterator</code> return the current variable value.
					Listeners to the <code class="literal">create variable</code> statement subscribe to changes in variable value: the runtime posts new and old value of the variable to all listeners when the variable value is updated by an <code class="literal">on set</code> statement.
				</p>
				<p>
					The example below creates a variable that provides a threshold value. The name of the variable is <code class="literal">var_threshold</code> and its type is <code class="literal">long</code>. The variable's initial value is <code class="literal">null</code> as no other value has been assigned:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create variable long var_threshold</pre>
				<p>
					This statement creates an integer-type variable named <code class="literal">var_output_rate</code> and initializes it to the value ten (10):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create variable integer var_output_rate = 10</pre>
				<p>
					The next statement declares a constant string-type variable:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create constant variable string const_filter_symbol = 'GE'</pre>
				<p>
					In addition to creating a variable via the <code class="literal">create variable</code> syntax, the configuration also allows adding variables. The next code snippet illustrates the
					use of the configuration API to declare a string-typed variable:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">Configuration configuration = new Configuration();
configuration.getCommon()..addVariable("myVar", String.class, "init value");</pre>
				<p>
					The following example declares a constant that is an array of string:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create constant variable string[] const_filters = {'GE', 'MSFT'}</pre>
				<p>
					The next example declares a constant that is an array of enumeration values. It assumes the <code class="literal">Color</code> enumeration class was imported:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create constant variable Color[] const_colors = {Color.RED, Color.BLUE}</pre>
				<p>
					For an array of primitive-type bytes, specify the <code class="literal">primitive</code> keyword in square brackets, as the next example shows:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create variable byte[primitive] mybytes = SomeClass.getBytes()</pre>
				<p>
					Use the <code class="literal">new</code> keyword to initialize object instances (the example assumes the package or class was imported):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create constant variable AtomicInteger cnt = new AtomicInteger(1)</pre>
				<p>
					The runtime removes the variable if the deployment that created the variable is undeployed.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="variable_set"></a>5.17.2. Setting Variable Values: The <code class="literal">On Set</code> Clause</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">on set</code> statement assigns a new value to one or more variables when a triggering event arrives or a triggering pattern occurs. Use the <code class="literal">setVariableValue</code> methods on <code class="literal">EPVariableService</code> to assign variable values programmatically.
				</p>
				<p>
					The synopsis for setting variable values is:
				</p>
				<pre class="synopsis">on <span class="emphasis"><em>event_type</em></span>[<span class="emphasis"><em>(filter_criteria)</em></span>] [as <span class="emphasis"><em>stream_name</em></span>]
  set <span class="emphasis"><em>mutation_expression</em></span>  [, <span class="emphasis"><em>mutation_expression</em></span> [,...]]
</pre>
				<p>
					The <span class="emphasis"><em>event_type</em></span> is the name of the type of events that trigger the variable assignments. It is optionally followed by <span class="emphasis"><em>filter_criteria</em></span> which are filter expressions to apply to arriving events. The optional <code class="literal">as</code> keyword can be used to assign an stream name. Patterns and named windows can also be specified in the <code class="literal">on</code> clause.
				</p>
				<p>
					After the <code class="literal">set</code> keyword follow one or more mutation expressions with variable names on the left hande side.
					The mutation expressions set the value of one or more variables. Subqueries may by part of expressions however aggregation functions and the <code class="literal">prev</code> or <code class="literal">prior</code> function may not be used in expressions.
				</p>
				<p>
					The below table lists the available mutation expessions:
				</p>
				<div class="table"><a id="d0e14662"></a>
					<p class="title"><b>Table 5.8. Mutation Expressions in Update-Set for Use With Variables</b></p>
					<div class="table-contents">
						<table summary="Mutation Expressions in Update-Set for Use With Variables" border="1">
							<colgroup>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th>Description</th>
									<th>Syntax and Examples</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>Assignment</td>
									<td>
										<pre class="synopsis"><span class="emphasis"><em>variable_name</em></span> = <span class="emphasis"><em>value_expression</em></span></pre>
										<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">price = 10, side = 'BUY'</pre>
									</td>
								</tr>
								<tr>
									<td>Array Element Assignment</td>
									<td>
										<pre class="synopsis"><span class="emphasis"><em>arrayvariable_name</em></span>[<span class="emphasis"><em>array_index_expression</em></span>] = <span class="emphasis"><em>value_expression</em></span></pre>
										<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">values[position] = 10</pre>
									</td>
								</tr>
								<tr>
									<td>Event Property Assignment</td>
									<td>
										<pre class="synopsis"><span class="emphasis"><em>eventvariable_name</em></span>.<span class="emphasis"><em>subproperty_name</em></span> = <span class="emphasis"><em>value_expression</em></span></pre>
										<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">myevent.price = 10</pre>
									</td>
								</tr>
								<tr>
									<td>Any Expression, For Example: User-Defined Function Call</td>
									<td>
										<pre class="synopsis"><span class="emphasis"><em>functionname</em></span>(..., <span class="emphasis"><em>variable_name</em></span>, ...)</pre>
										<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">clearQuantities(variable)</pre>
										<p>Requires the use of a single variable as part of each mutation expression.</p>
									</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
				<p>
					All new variable values are applied atomically: the changes to variable values by the <code class="literal">on set</code> statement
					become visible to other statements all at the same time. No changes are visible to other processing threads until the <code class="literal">on set</code> statement completed processing, and at that time all changes become visible at once.
				</p>
				<p>
					The <code class="literal">EPStatement</code> object provides access to variable values. The pull API methods <code class="literal">iterator</code> and <code class="literal">safeIterator</code> return the current variable values for each of the variables set by the statement.
					Listeners to the statement subscribe to changes in variable values: the runtime posts new variable values of all variables to any listeners.
				</p>
				<p>
					In the following example, a variable by name <code class="literal">var_output_rate</code> has been declared previously. When a NewOutputRateEvent event arrives, the variable is updated to a new value supplied by the event property 'rate':
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on NewOutputRateEvent set var_output_rate = rate</pre>
				<p>
					The next example shows two variables that are updated when a ThresholdUpdateEvent arrives:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on ThresholdUpdateEvent as t 
  set var_threshold_lower = t.lower,
      var_threshold_higher = t.higher</pre>
				<p>
					The sample statement shown next counts the number of pattern matches using a variable. The pattern looks for OrderEvent events that are followed by CancelEvent events for the same order id within 10 seconds of the OrderEvent:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on pattern[every a=OrderEvent -&gt; (CancelEvent(orderId=a.orderId) where timer:within(10 sec))]
  set var_counter = var_counter + 1</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="variable_using"></a>5.17.3. Using Variables</h3>
						</div>
					</div>
				</div>
				<p>
					A variable name can be used in any expression and can also occur in an output rate limiting clause. This section presents examples and discusses performance, consistency and atomicity attributes of variables.
				</p>
				<p>
					The next statement assumes that a variable named 'var_threshold' was created to hold a total price threshold value.
					The statement outputs an event when the total price for a symbol is greater then the current threshold value:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, sum(price) from TickEvent 
group by symbol 
having sum(price) &gt; var_threshold</pre>
				<p>
					This example uses a variable to dynamically change the output rate on-the-fly. The variable 'var_output_rate' holds the current rate at which the statement posts a current count to listeners:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*) from TickEvent output every var_output_rate seconds</pre>
				<p>
					Variables are optimized towards high read frequency and lower write frequency. Variable reads do not incur locking overhead (99% of the time) while variable writes do incur locking overhead.
				</p>
				<p>
					The runtime softly guarantees consistency and atomicity of variables when your statement executes in response to an event or timer invocation. Variables acquire a stable value (implemented by versioning) when your statement starts executing in response to an event or timer invocation, and variables do not change value during execution. When one or more variable values are updated via <code class="literal">on set</code> statements, the changes to all updated variables become visible to statements as one unit and only when the <code class="literal">on set</code> statement completes successfully.
				</p>
				<p>
					The atomicity and consistency guarantee is a soft guarantee. If any of your application statements, in response to an event or timer invocation, execute for a time interval longer then 15 seconds (default interval length), then the runtime may use current variable values after 15 seconds passed, rather then then-current variable values at the time the statement started executing in response to an event or timer invocation.
				</p>
				<p>
					The length of the time interval that variable values are held stable for the duration of execution of a given statement is by default 15 seconds, but can be configured via runtime settings.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="variable_object"></a>5.17.4. Object-Type Variables</h3>
						</div>
					</div>
				</div>
				<p>
					A variable of type <code class="literal">object</code> (or <code class="literal">java.lang.Object</code> via the API) can be assigned any value including null. When using an object-type variable in an expression, your statement may need to cast the
					value to the desired type.
				</p>
				<p>
					The following sample EPL creates a variable by name <code class="literal">varobj</code> of type object:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create variable object varobj</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="variable_eventtype"></a>5.17.5. Class and Event-Type Variables</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">create variable</code> syntax and the API accept a fully-qualified class name or alternatively the name of an event type. This is useful when you want a single variable to have multiple property values to read or set.
				</p>
				<p>
					The next statement assumes that the event type <code class="literal">PageHitEvent</code> is declared:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create variable PageHitEvent varPageHitZero</pre>
				<p>
					These example statements show two ways of assigning to the variable:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// You may assign the complete event
on PageHitEvent(ip='0.0.0.0') pagehit set varPageHitZero = pagehit</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Or assign individual properties of the event
on PageHitEvent(ip='0.0.0.0') pagehit set varPageHitZero.userId = pagehit.userId</pre>
				<p>
					Similarly statements may use properties of class or event-type variables as this example shows:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from FirewallEvent(userId=varPageHitZero.userId)</pre>
				<p>
					Instance method can also be invoked:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create variable com.example.StateCheckerService stateChecker</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from TestEvent as e where stateChecker.checkState(e)</pre>
				<p>
					A variable that represents a service for calling instance methods could be initialized by calling a factory method. This example assumes the classes were added to imports:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create constant variable StateCheckerService stateChecker = StateCheckerServiceFactory.makeService()</pre>
				<p>
					You can add a variable via the configuration API; an example code snippet is next:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">Configuration configuration = new Configuration();
configuration.getCommon().addVariable("stateChecker", StateCheckerService.class, StateCheckerServiceFactory.makeService(), true);</pre>
				<p>
					Application objects can also be passed via transient configuration information as described in <a class="xref" href="configuration.html#configuration-transientobjects" title="17.7. Passing Services or Transient Objects">Section 17.7, “Passing Services or Transient Objects”</a>.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					When using non-constant class or event-type variables and when your EPL intends to set property values on the variable itself (i.e. <code class="literal">set varPageHitZero.userId</code>), please note the following requirements. In order for the runtime to assign property values, the underlying event type must allow writing property values. If using JavaBean event classes the class must have setter methods and a default constructor. The underlying event type must also be copy-able i.e. implement <code class="literal">Serializable</code> or configure a copy method (only for non-constant variables and when setting property values).
				</div>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="create-exprglobal"></a>5.18. Declaring Global Expressions, Aliases and Scripts: <span class="emphasis"><em>Create Expression</em></span></h2>
					</div>
				</div>
			</div><a id="d0e14880" class="indexterm"></a><a id="d0e14883" class="indexterm"></a><a id="d0e14888" class="indexterm"></a>
			<p>
				Your application can declare an expression or script using the <code class="literal">create expression</code> clause. Such expressions or scripts become available
				globally to any statement.
			</p>
			<p>
				The synopsis of the <code class="literal">create expression</code> syntax is:
			</p>
			<pre class="synopsis">create expression <span class="emphasis"><em>expression_or_script</em></span></pre>
			<p>
				Use the <code class="literal">create expression</code> keywords and append the expression or scripts.
			</p>
			<p>
				Expression aliases are the simplest means of sharing expressions and do not accept parameters.
				Expression declarations limit the expression scope to the parameters that are passed.
			</p>
			<p>
				The runtime may cache declared expression result values and reuse cache values, see <a class="xref" href="configuration.html#configuration-runtime-execution-declaredexprvaluecachesize" title="17.6.10.6. Declared Expression Value Cache Size">Section 17.6.10.6, “Declared Expression Value Cache Size”</a>.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="create-exprglobal-alias"></a>5.18.1. Global Expression Aliases</h3>
						</div>
					</div>
				</div>
				<p>
					The syntax and additional examples for declaring an expression is outlined in <a class="xref" href="epl_clauses.html#epl-syntax-expression-alias" title="5.2.8. Expression Alias">Section 5.2.8, “Expression Alias”</a>,
					which discusses expression aliases that are visible within the same statement i.e. visible locally only.
				</p>
				<p>
					When using the <code class="literal">create expression</code> syntax to declare an expression the runtime remembers the expression alias and expression
					and allows the alias to be referenced in all other statements.
				</p>
				<p>
					The below EPL declares a globally visible expression alias for an expression that computes the total of the mid-price which is the buy and sell price divided by two:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create expression totalMidPrice alias for { sum((buy + sell) / 2) }</pre>
				<p>
					The next EPL returns mid-price for events for which the mid-price per symbol stays below 10:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, midPrice from MarketDataEvent group by symbol having midPrice &lt; 10</pre>
				<p>
					The expression name must be unique among all other expression aliases and expression declarations.
				</p>
				<p>
					Your application can provide an expression alias of the same name local to a given statement as well as globally using <code class="literal">create expression</code>.
					The locally-provided expression alias overrides the global expression alias.
				</p>
				<p>
					The compiler validates global expression aliases at the time your application creates a statement that references the alias.
					When a statement references a global alias, the compiler uses the that statement's local expression scope to validate the expression.
					Expression aliases can therefore be dynamically typed and type information does not need to be the same
					for all statements that reference the expression alias.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="create-exprglobal-expr"></a>5.18.2. Global Expression Declarations</h3>
						</div>
					</div>
				</div>
				<p>
					The syntax and additional examples for declaring an expression is outlined in <a class="xref" href="epl_clauses.html#epl-syntax-expression-decl" title="5.2.9. Expression Declaration">Section 5.2.9, “Expression Declaration”</a>,
					which discusses declaring expressions that are visible within the same statement i.e. visible locally only.
				</p>
				<p>
					When using the <code class="literal">create expression</code> syntax to declare an expression the compiler remembers the expression
					and allows the expression to be referenced in all other statements.
				</p>
				<p>
					The below EPL declares a globally visible expression that computes a mid-price and that requires a single parameter:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create expression midPrice { in =&gt; (buy + sell) / 2 }</pre>
				<p>
					The next EPL returns mid-price for each event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select midPrice(md) from MarketDataEvent as md</pre>
				<p>
					The expression name must be unique for global expressions. It is not possible to declare the same global expression twice with the same name.
				</p>
				<p>
					Your application can declare an expression of the same name local to a given statement as well as globally using <code class="literal">create expression</code>.
					The locally-declared expression overrides the globally declared expression.
				</p>
				<p>
					The compiler validates globally declared expressions at the time your application creates a statement that references the global expression.
					When a statement references a global expression, the compiler uses that statement's type information to validate the global expressions.
					Global expressions can therefore be dynamically typed and type information does not need to be the same
					for all statements that reference the global expression.
				</p>
				<p>
					This example shows a sequence of EPL, that can be created in the order shown, and that demonstrates expression validation at time of referral:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create expression minPrice {(select min(price) from OrderWindow)}</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create window OrderWindow#time(30) as OrderEvent</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into OrderWindow select * from OrderEvent</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Validates and incorporates the declared global expression
select minPrice() as minprice from MarketData</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="create-exprglobal-script"></a>5.18.3. Global Scripts</h3>
						</div>
					</div>
				</div>
				<p>
					The syntax and additional examples for declaring scripts is outlined in <a class="xref" href="script.html" title="Chapter 19. Script Support">Chapter 19, <i>Script Support</i></a>,
					which discusses declaring scripts that are visible within the same statement i.e. visible locally only.
				</p>
				<p>
					When using the <code class="literal">create expression</code> syntax to declare a script the compiler remembers the script
					and allows the script to be referenced in all other statements.
				</p>
				<p>
					The below EPL declares a globally visible script in the JavaScript dialect that computes a mid-price:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create expression midPrice(buy, sell) [ (buy + sell) / 2 ]</pre>
				<p>
					The next EPL returns mid-price for each event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select midPrice(buy, sell) from MarketDataEvent</pre>
				<p>
					The compiler validates globally declared scripts at the time your application creates a statement that references the global script.
					When a statement references a global script, the compiler uses that statement's type information to determine parameter types.
					Global scripts can therefore be dynamically typed and type information does not need to be the same
					for all statements that reference the global script.
				</p>
				<p>
					The script name in combination with the number of parameters must be unique for global scripts.
					It is not possible to declare the same global script twice with the same name and number of parameters.
				</p>
				<p>
					Your application can declare a script of the same name and number of parameters that is local to a given statement as well as globally using <code class="literal">create expression</code>.
					The locally-declared script overrides the globally declared script.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-containedeventselect"></a>5.19. Contained-Event Selection</h2>
					</div>
				</div>
			</div>
			<p>
				Contained-event selection is for use when an event contains properties that are themselves events, or more generally when your application needs to split or explode an event into multiple events. One example is when application events are coarse-grained structures and you need to perform bulk operations on the rows of the property graph in an event.
			</p>
			<p>
				Use the contained-event selection syntax in a filter expression such as in a pattern, <code class="literal">from</code> clause, subselect, on-select and on-delete. This section provides the synopsis and examples.
			</p>
			<p>
				To review, in the <code class="literal">from</code> clause a <span class="emphasis"><em>contained_selection</em></span> may appear after the event stream name and filter criteria, and before any data windows.
			</p>
			<p>
				The synopsis for <span class="emphasis"><em>contained_selection</em></span> is as follows:
			</p>
			<pre class="synopsis">[select <span class="emphasis"><em>select_expressions</em></span> from] 
  <span class="emphasis"><em>contained_expression</em></span> [@type(<span class="emphasis"><em>eventtype_name</em></span>)] [as <span class="emphasis"><em>alias_name</em></span>]
  [where <span class="emphasis"><em>filter_expression</em></span>]</pre>
			<p>
				The <code class="literal">select</code> clause and <span class="emphasis"><em>select_expressions</em></span> are optional and may be used to select specific properties of contained events.
			</p>
			<p>
				The <span class="emphasis"><em>contained_expression</em></span> is required and returns individual events. The expression can, for example, be an event property name that returns an event fragment, i.e. a property that can itself be represented as an event by the underlying event representation. The expression can also be any other expression such as a single-row function or a script that returns either an array or a <code class="literal">java.util.Collection</code> of events. Simple values such as integer or string are not fragments but can be used as well as described below.
			</p>
			<p>
				Provide the <code class="literal">@type(name)</code> annotation after the contained expression to name the event type of events returned by the expression. The annotation is optional and not needed when the contained-expression is an event property that returns a class or other event fragment.
			</p>
			<p>
				The <span class="emphasis"><em>alias_name</em></span> can be provided to assign a name to the expression result value rows.
			</p>
			<p>
				The <code class="literal">where</code> clause and <span class="emphasis"><em>filter_expression</em></span> is optional and may be used to filter out properties.
			</p>
			<p>
				As an example event, consider a media order. A media order consists of order items as well as product descriptions. A media order event can be represented as an object graph (POJO event representation), or a structure of nested Maps (Map event representation) or a XML document (XML DOM or Axiom event representation) or other custom plug-in event representation.
			</p>
			<p>
				To illustrate, a sample media order event in XML event representation is shown below. Also, a XML event type can optionally be strongly-typed with an explicit XML XSD schema that is not shown here. Note that Map and POJO representation can be considered equivalent for the purpose of this example.
			</p>
			<p>
				Let us now assume the event type <code class="literal">MediaOrder</code> as being represented by the root node <code class="literal">&lt;mediaorder&gt;</code> of such XML snip:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">&lt;mediaorder&gt;
  &lt;orderId&gt;PO200901&lt;/orderId&gt;
  &lt;items&gt;
    &lt;item&gt;
      &lt;itemId&gt;100001&lt;/itemId&gt;
      &lt;productId&gt;B001&lt;/productId&gt;
      &lt;amount&gt;10&lt;/amount&gt;
      &lt;price&gt;11.95&lt;/price&gt;
    &lt;/item&gt;
  &lt;/items&gt;
  &lt;books&gt;
    &lt;book&gt;
      &lt;bookId&gt;B001&lt;/bookId&gt;
      &lt;author&gt;Heinlein&lt;/author&gt;
      &lt;review&gt;
        &lt;reviewId&gt;1&lt;/reviewId&gt;
        &lt;comment&gt;best book ever&lt;/comment&gt;
      &lt;/review&gt;
    &lt;/book&gt;
    &lt;book&gt;
      &lt;bookId&gt;B002&lt;/bookId&gt;
      &lt;author&gt;Isaac Asimov&lt;/author&gt;
    &lt;/book&gt;
  &lt;/books&gt;
&lt;/mediaorder&gt;</pre>
			<p>
				The next statement utilizes the contained-event selection syntax to return each book:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder[books.book]</pre>
			<p>
				The result of the above statement is one event per book. Output events contain only the book properties and not any of the mediaorder-level properties.
			</p>
			<p>
				Note that, when using listeners, the runtime delivers multiple results in one invocation of each listener. Therefore listeners to the above statement can expect a single invocation passing all book events within one media order event as an array.
			</p>
			<p>
				To better illustrate the position of the contained-event selection syntax in a statement, consider the next two statements:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder(orderId='PO200901')[books.book]</pre>
			<p>
				The above statement the returns each book only for media orders with a given order id. This statement illustrates a contained-event selection and a data window:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*) from MediaOrder[books.book]#unique(bookId)</pre>
			<p>
				The sample above counts each book unique by book id.
			</p>
			<p>
				Contained-event selection can be staggered. When staggering multiple contained-event selections the staggered contained-event selection is relative to its parent.
			</p>
			<p>
				This example demonstrates staggering contained-event selections by selecting each review of each book:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder[books.book][review]</pre>
			<p>
				Listeners to the statement above receive a row for each review of each book. Output events contain only the review properties and not the book or media order properties.
			</p>
			<p>
				The following is not valid:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// not valid
select * from MediaOrder[books.book.review]</pre>
			<p>
				The <code class="literal">book</code> property in an indexed property (an array or collection) and thereby requires an index in order to determine which book to use. The expression <code class="literal">books.book[1].review</code> is valid and means all reviews of the second (index 1) book.
			</p>
			<p>
				The contained-event selection syntax is part of the filter expression and may therefore occur in patterns and anywhere a filter expression is valid.
			</p>
			<p>
				A pattern example is below. The example assumes that a <code class="literal">Cancel</code> event type has been defined that also has an <code class="literal">orderId</code> property:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from pattern [c=Cancel -&gt; books=MediaOrder(orderId = c.orderId)[books.book] ]</pre>
			<p>
				When used in a pattern, a filter with a contained-event selection returns an array of events, similar to the match-until clause in patterns. The above statement returns, in the <code class="literal">books</code> property, an
				array of book events.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-select"></a>5.19.1. Select-Clause in a Contained-Event Selection</h3>
						</div>
					</div>
				</div>
				<p>
					The optional <code class="literal">select</code> clause provides control over which fields are available in output events. The expressions in the select-clause apply only to the properties available underneath the property in the <code class="literal">from</code> clause, and the properties of the enclosing event.
				</p>
				<p>
					When no <code class="literal">select</code> is specified, only the properties underneath the selected property are available in output events.
				</p>
				<p>
					In summary, the <code class="literal">select</code> clause may contain:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Any expressions, wherein properties are resolved relative to the property in the <code class="literal">from</code> clause.
							</p>
						</li>
						<li>
							<p>
								Use the wildcard (<code class="literal">*</code>) to provide all properties that exist under the property in the <code class="literal">from</code> clause.
							</p>
						</li>
						<li>
							<p>
								Use the <span class="emphasis"><em>alias_name</em></span><code class="literal">.*</code> syntax to provide all properties that exist under a property in the <code class="literal">from</code> clause.
							</p>
						</li>
					</ol>
				</div>
				<p>
					The next statement's <code class="literal">select</code> clause selects each review for each book, and the order id as well as the book id of each book:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder[select orderId, bookId from books.book][select * from review]
// ... equivalent to ...
select * from MediaOrder[select orderId, bookId from books.book][review]]</pre>
				<p>
					Listeners to the statement above receive an event for each review of each book. Each output event has all properties of the review row, and in addition the <code class="literal">bookId</code> of each book and the <code class="literal">orderId</code> of the order.
					Thus <code class="literal">bookId</code> and <code class="literal">orderId</code> are found in each result event, duplicated when there are multiple reviews per book and order.
				</p>
				<p>
					The above statement uses wildcard <code class="literal">(*)</code> to select all properties from reviews. As has been discussed as part of the <code class="literal">select</code> clause, the wildcard (<code class="literal">*</code>) and <span class="emphasis"><em>property_alias</em></span><code class="literal">.*</code> do not copy properties for performance reasons. The wildcard syntax instead specifies the underlying type, and additional properties are added onto that underlying type if required. Only one wildcard (<code class="literal">*</code>) and <span class="emphasis"><em>property_alias</em></span><code class="literal">.*</code> (unless used with a column rename) may therefore occur in the <code class="literal">select</code> clause list of expressions.
				</p>
				<p>
					All the following statements produce an output event for each review of each book. The next sample statements illustrate the options available to control the fields of output events.
				</p>
				<p>
					The output events produced by the next statement have all properties of each review and no other properties available:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder[books.book][review]</pre>
				<p>
					The following statement is not a valid statement, since the order id and book id are not part of the contained-event selection:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Invalid select-clause: orderId and bookId not produced.
select orderId, bookId from MediaOrder[books.book][review]</pre>
				<p>
					This statement is valid. Note that output events carry only the <code class="literal">orderId</code> and <code class="literal">bookId</code> properties and no other data:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select orderId, bookId from MediaOrder[books.book][select orderId, bookId from review]
//... equivalent to ...
select * from MediaOrder[select orderId, bookId from books.book][review]</pre>
				<p>
					This variation produces output events that have all properties of each book and only <code class="literal">reviewId</code> and <code class="literal">comment</code> for each review:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder[select * from books.book][select reviewId, comment from review]
// ... equivalent to ...
select * from MediaOrder[books.book as book][select book.*, reviewId, comment from review]</pre>
				<p>
					The output events of the next EPL have all properties of the order and only <code class="literal">bookId</code> and <code class="literal">reviewId</code> for each review:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder[books.book as book]
    [select mediaOrder.*, bookId, reviewId from review] as mediaOrder</pre>
				<p>
					This EPL produces output events with 3 columns: a column named <code class="literal">mediaOrder</code> that is the order itself, a column named <code class="literal">book</code> for each book and a column named <code class="literal">review</code> that holds each review:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into ReviewStream select * from MediaOrder[books.book as book]
  [select mo.* as mediaOrder, book.* as book, review.* as review from review as review] as mo</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// .. and a sample consumer of ReviewStream...
select mediaOrder.orderId, book.bookId, review.reviewId from ReviewStream</pre>
				<p>
					Please note these limitations:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Sub-selects, aggregation functions and the <code class="literal">prev</code> and <code class="literal">prior</code> operators are not available in contained-event selection.
							</p>
						</li>
						<li>
							<p>
								Expressions in the <code class="literal">select</code> and <code class="literal">where</code> clause of a contained-event selection can only reference properties relative to the current event and property.
							</p>
						</li>
					</ol>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-where"></a>5.19.2. Where Clause in a Contained-Event Selection</h3>
						</div>
					</div>
				</div>
				<p>
					The optional <code class="literal">where</code> clause may be used to filter out properties at the same level that the where-clause occurs.
				</p>
				<p>
					The properties in the filter expression must be relative to the property in the <code class="literal">from</code> clause or the enclosing event.
				</p>
				<p>
					This statement outputs all books with a given author:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder[books.book where author = 'Heinlein']</pre>
				<p>
					This statement outputs each review of each book where a review comment contains the word 'good':
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MediaOrder[books.book][review where comment like 'good']</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-join"></a>5.19.3. Contained-Event Selection and Joins</h3>
						</div>
					</div>
				</div>
				<p>
					This section discusses contained-event selection in joins.
				</p>
				<p>
					When joining within the same event it is not required to specify a data window. Recall, in a join or outer join there must be a data window specified that defines the subset of events available to be joined. For self-joins, no data window is required and the join
					executes against the data returned by the same event.
				</p>
				<p>
					This statement inner-joins items to books where book id matches the product id:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select book.bookId, item.itemId 
from MediaOrder[books.book] as book, 
      MediaOrder[items.item] as item 
where productId = bookId</pre>
				<p>
					Statement results for the above statement when sending the media order event as shown earlier are:
				</p>
				<div class="informaltable">
					<table border="1">
						<colgroup>
							<col>
							<col>
						</colgroup>
						<thead>
							<tr>
								<th>book.bookId</th>
								<th>item.itemId</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>B001</td>
								<td>100001</td>
							</tr>
						</tbody>
					</table>
				</div>
				<p>
					The next example statement is a left outer join. It returns all books and their items, and for books without item it returns the book and a <code class="literal">null</code> value:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select book.bookId, item.itemId 
from MediaOrder[books.book] as book 
  left outer join 
    MediaOrder[items.item] as item 
  on productId = bookId</pre>
				<p>
					Statement results for the above statement when sending the media order event as shown earlier are:
				</p>
				<div class="informaltable">
					<table border="1">
						<colgroup>
							<col>
							<col>
						</colgroup>
						<thead>
							<tr>
								<th>book.bookId</th>
								<th>item.itemId</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>B001</td>
								<td>100001</td>
							</tr>
							<tr>
								<td>B002</td>
								<td>null</td>
							</tr>
						</tbody>
					</table>
				</div>
				<p>
					A full outer join combines the results of both left and right outer joins. The joined table will contain all records from both tables, and fill in <code class="literal">null</code> values for missing matches on either side.
				</p>
				<p>
					This example statement is a full outer join, returning all books as well as all items, and filling in <code class="literal">null</code> values for book id or item id if no match is found:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select orderId, book.bookId,item.itemId 
from MediaOrder[books.book] as book 
  full outer join 
     MediaOrder[select orderId, * from items.item] as item 
  on productId = bookId 
order by bookId, item.itemId asc
</pre>
				<p>
					As in all other statements, aggregation results are cumulative from the time the statement was created.
				</p>
				<p>
					The following statement counts the cumulative number of items in which the product id matches a book id:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*) 
from MediaOrder[books.book] as book, 
      MediaOrder[items.item] as item 
where productId = bookId</pre>
				<p>
					The <code class="literal">unidirectional</code> keyword in a join indicates to the runtime that aggregation state is not cumulative. The next statement counts the number of items in which the product id matches a book id for each event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*) 
from MediaOrder[books.book] as book unidirectional, 
      MediaOrder[items.item] as item 
where productId = bookId</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-pojoexample"></a>5.19.4. Sentence and Word Example</h3>
						</div>
					</div>
				</div>
				<p>
					The next example splits an event representing a sentence into multiple events in which each event represents a word. It represents all events and the logic to split events into contained events as Java code.
					The next chapter has additional examples that use Map-type events and put contained-event logic into a separate expression or script.
				</p>
				<p>
					The sentence event in this example is represented by a class declared as follows:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class SentenceEvent {
  private final String sentence;

  public SentenceEvent(String sentence) {
    this.sentence = sentence;
  }

  public WordEvent[] getWords() {
    String[] split = sentence.split(" ");
    WordEvent[] words = new WordEvent[split.length];
    for (int i = 0; i &lt; split.length; i++) {
      words[i] = new WordEvent(split[i]);
    }
    return words;
  }
}</pre>
				<p>
					The sentence event as above provides an event property <code class="literal">words</code> that returns each word event.
				</p>
				<p>
					The declaration of word event is also a class:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class WordEvent {
  private final String word;

  public WordEvent(String word) {
    this.word = word;
  }

  public String getWord() {
    return word;
  }
}</pre>
				<p>
					The statement to populate a stream of words from a sentence event is:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into WordStream select * from SentenceEvent[words]</pre>
				<p>
					Finally, the API call to send a sentence event to the runtime is shown here:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">runtime.getEventService().sendEventBean(new SentenceEvent("Hello Word Contained Events"), "SentenceEvent");</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-examples"></a>5.19.5. More Examples</h3>
						</div>
					</div>
				</div>
				<p>
					The examples herein are not based on the POJO events of the prior example. They are meant to demonstrate different types of contained-event expressions and the use of <code class="literal">@type(</code><span class="emphasis"><em>type_name</em></span><code class="literal">)</code> to identify the event type of the return values of the contained-event expression.
				</p>
				<p>
					The example first defines a few sample event types:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema SentenceEvent(sentence String)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema WordEvent(word String)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema CharacterEvent(char String)</pre>
				<p>
					The following EPL assumes that your application defined a plug-in single-row function by name <code class="literal">splitSentence</code> that returns an array of Map, producting output events that are <code class="literal">WordEvent</code> events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into WordStream select * from SentenceEvent[splitSentence(sentence)@type(WordEvent)]</pre>
				<p>
					The example EPL shown next invokes a JavaScript function which returns some events of type <code class="literal">WordEvent</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">expression Collection js:splitSentenceJS(sentence) [
  var CollectionsClazz = Java.type('java.util.Collections');
  var words = new java.util.ArrayList();
  words.add(CollectionsClazz.singletonMap('word', 'wordOne'));
  words.add(CollectionsClazz.singletonMap('word', 'wordTwo'));
  words;
]
select * from SentenceEvent[splitSentenceJS(sentence)@type(WordEvent)]</pre>
				<p>
					In the next example the sentence event first gets split into words and then each word event gets split into character events via an additional <code class="literal">splitWord</code> single-row function,
					producing events of type <code class="literal">CharacterEvent</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from SentenceEvent
  [splitSentence(sentence)@type(WordEvent)]
  [splitWord(word)@type(CharacterEvent)]</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-arrayofprimitive"></a>5.19.6. Contained Expression Returning an Array of Property Values</h3>
						</div>
					</div>
				</div>
				<p>
					Your <span class="emphasis"><em>contained_expression</em></span> may return an array of property values such as an array of integer or string values.
					In this case you must specify a <code class="literal">@type(name)</code> annotation and provide an event type name that declares a single column with a type that matches the array component type.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema IdContainer(id int)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema MyEvent(ids int[])</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MyEvent[ids@type(IdContainer)]</pre>
				<p>
					This example declares a named window and uses on-delete:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create window MyWindow#keepall (id int)</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">on MyEvent[ids@type(IdContainer)] as my_ids 
delete from MyWindow my_window 
where my_ids.id = my_window.id</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-arrayofevent"></a>5.19.7. Contained Expression Returning an Array of EventBean</h3>
						</div>
					</div>
				</div>
				<p>
					Your <span class="emphasis"><em>contained_expression</em></span> may return an array of <code class="literal">EventBean</code> instances.
					This is handy when the expression itself must decide the type of each event to return.
				</p>
				<p>
					For example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema BaseEvent();</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema AEvent(pa string) inherits BaseEvent;</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema BEvent(pb string) inherits BaseEvent;</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">create schema ValueEvent(value string);</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from ValueEvent[mySplitFunction(value) @type(BaseEvent)]</pre>
				<p>
					Then declare <code class="literal">mySplitFunction</code> returning an array of events, such as:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public static EventBean[] mySplitFunction(String value, EPLMethodInvocationContext context) {
  EventBean[] events = new EventBean[1];
  if (value.startsWith("A")) {
    events[0] =  context.getEventBeanService().adapterForMap(Collections.singletonMap("pa", value), "AEvent");
  }
  else {
    events[0] =  context.getEventBeanService().adapterForMap(Collections.singletonMap("pb", value), "BEvent");
  }
  return events;
}</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-collectionofundeventobj"></a>5.19.8. Contained Expression Returning a Collection of Underlying Event Objects</h3>
						</div>
					</div>
				</div>
				<p>
					Your <span class="emphasis"><em>contained_expression</em></span> may return a collection of underlying event instances.
				</p>
				<p>
					In this example the <code class="literal">selectFrom</code> enumeration method formats subquery results and returns a collection of Map instances.
					Since Map is the underlying event object for Map-type event types, each Map with the room id can be processed as an event by the contained event syntax.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Declare Person and Room event types, represented as java.util.Map events (the default)
@public @buseventtype create schema Person(personId string);
@public @buseventtype create schema Room(roomId string);

// Have a window that holds all rooms
create window RoomWindow#keepall as Room;
insert into RoomWindow select * from Room;

// Output all rooms ids as a collection of maps into the "rooms" column 
insert into PersonAndRooms select personId, (select roomId from RoomWindow).selectFrom(v =&gt; new {roomId = v}) as rooms from Person;

// Select each combination of person and room
@Name('s0') select personId, roomId from PersonAndRooms[select personId, roomId from rooms@type(Room)];</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-beginend"></a>5.19.9. Generating Marker Events Such as a Begin and End Event</h3>
						</div>
					</div>
				</div>
				<p>
					The syntax for splitting and duplicating streams can be used to generate marker events.
					Please see <a class="xref" href="epl_clauses.html#split_containedeventselect" title="5.16.1. Generating Marker Events for Contained Events">Section 5.16.1, “Generating Marker Events for Contained Events”</a> for more information.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-containedeventselect-restrictions"></a>5.19.10. Contained-Event Limitations</h3>
						</div>
					</div>
				</div>
				<p>
					The following restrictions apply to contained-event selection:
				</p>
				<div class="itemizedlist">
					<ul compact="compact">
						<li>
							<p>
								When selecting contained events from a named window in a join, the stream must be marked as <code class="literal">unidirectional</code>.
							</p>
						</li>
						<li>
							<p>
								Selecting contained events from a named window in a correlated subquery is not allowed.
							</p>
						</li>
					</ul>
				</div>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-update"></a>5.20. Updating an Insert Stream: The <code class="literal">Update IStream</code> Clause</h2>
					</div>
				</div>
			</div>
			<p>
				The <code class="literal">update istream</code> statement allows declarative modification of event properties of events entering a stream. Update is a pre-processing step to each new event, modifying an event before the event applies to any statements.
			</p>
			<p>
				The synopsis of <code class="literal">update istream</code> is as follows:
			</p>
			<pre class="synopsis">update istream <span class="emphasis"><em>event_type</em></span> [as <span class="emphasis"><em>stream_name</em></span>]
  set <span class="emphasis"><em>mutation_expression</em></span> [, <span class="emphasis"><em>mutation_expression</em></span>] [,...]
  [where <span class="emphasis"><em>where_expression</em></span>]
</pre>
			<p>
				The <span class="emphasis"><em>event_type</em></span> is the name of the type of events that the <code class="literal">update</code> applies to.
				The optional <code class="literal">as</code> keyword can be used to assign a name to the event type for use with subqueries, for example.
			</p>
			<p>
				After the <code class="literal">set</code> keyword follow one or more mutation expressions. The below table lists the available mutation expessions:
			</p>
			<div class="table"><a id="d0e15647"></a>
				<p class="title"><b>Table 5.9. Mutation Expressions in <code class="literal">Update IStream</code></b></p>
				<div class="table-contents">
					<table summary="Mutation Expressions in Update IStream" border="1">
						<colgroup>
							<col>
							<col>
						</colgroup>
						<thead>
							<tr>
								<th>Description</th>
								<th>Syntax and Examples</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>Assignment</td>
								<td>
									<pre class="synopsis"><span class="emphasis"><em>property_name</em></span> = <span class="emphasis"><em>value_expression</em></span></pre>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">price = 10, side = 'BUY'</pre>
								</td>
							</tr>
							<tr>
								<td>Array Element Assignment</td>
								<td>
									<pre class="synopsis"><span class="emphasis"><em>arrayproperty_name</em></span>[<span class="emphasis"><em>array_index_expression</em></span>] = <span class="emphasis"><em>value_expression</em></span></pre>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">values[position] = 10</pre>
								</td>
							</tr>
							<tr>
								<td>Any Expression, For Example: User-Defined Function Call</td>
								<td>
									<pre class="synopsis"><span class="emphasis"><em>functionname</em></span>(alias)</pre>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">clearQuantities(myevent)</pre>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div><br class="table-break">
			<p>
				The optional <code class="literal">where</code> clause and expression can be used to filter out events to which to apply updates.
			</p>
			<p>
				Listeners to an <code class="literal">update</code> statement receive the updated event in the insert stream (new data) and the event prior to the update in the remove stream (old data). Note that if there are multiple update statements that all apply to the same event then the runtime will ensure that the output events delivered to listeners or subscribers are consistent with the then-current updated properties of the event (if necessary making event copies, as described below, in the case that listeners are attached to update statements). Iterating over an update statement returns no events.
			</p>
			<p>
				As an example, the below statement assumes an <code class="literal">AlertEvent</code> event type that has properties named <code class="literal">severity</code> and <code class="literal">reason</code>:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">update istream AlertEvent 
  set severity = 'High'
  where severity = 'Medium' and reason like '%withdrawal limit%'</pre>
			<p>
				The statement above changes the value of the <code class="literal">severity</code> property to "High" for <code class="literal">AlertEvent</code> events that have a medium severity and contain a specific reason text.
			</p>
			<p>
				Update statements apply the changes to event properties before other statements receive the event(s) for processing, e.g. "<code class="literal">select * from AlertEvent</code>" receives the updated <code class="literal">AlertEvent</code>. This is true regardless of the order in which your application creates statements.
			</p>
			<p>
				When multiple update statements apply to the same event, the runtime executes updates in the order in which update statements were deployed. We recommend the <code class="literal">@Priority</code> EPL annotation to define a deterministic order of processing updates, especially in the case where update statements get deployed and undeployed dynamically or multiple update statements update the same fields. The update statement with the highest <code class="literal">@Priority</code> value applies last.
			</p>
			<p>
				The <code class="literal">update</code> clause can be used on streams populated via <code class="literal">insert into</code>, as this example utilizing a pattern demonstrates:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">insert into DoubleWithdrawalStream 
select a.id, b.id, a.account as account, 0 as minimum 
from pattern [a=Withdrawal -&gt; b=Withdrawal(id = a.id)]</pre>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">update istream DoubleWithdrawalStream set minimum = 1000 where account in (10002, 10003)</pre>
			<p>
				When using <code class="literal">update istream</code> with named windows, any changes to event properties apply before an event enters the named window.
				The <code class="literal">update istream</code> is not available for tables.
			</p>
			<p>
				Consider the next example (shown here with statement names in @Name EPL annotation, multiple statements):
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@Name("CreateWindow") create window MyWindow#time(30 sec) as AlertEvent

@Name("UpdateStream") update istream MyWindow set severity = 'Low' where reason = '%out of paper%'

@Name("InsertWindow") insert into MyWindow select * from AlertEvent

@Name("SelectWindow") select * from MyWindow</pre>
			<p>
				The <code class="literal">UpdateStream</code> statement specifies an <code class="literal">update</code> clause that applies to all events entering the named window. Note that <code class="literal">update</code> does not apply to events already in the named window at the time an application creates the <code class="literal">UpdateStream</code> statement, it only applies to new events entering the named window (after an application created the <code class="literal">update</code> statement).
			</p>
			<p>
				Therefore, in the above example listeners to the <code class="literal">SelectWindow</code> statement as well as the <code class="literal">CreateWindow</code> statement receive the updated event,
				while listeners to the <code class="literal">InsertWindow</code> statement receive the original <code class="literal">AlertEvent</code> event (and not the updated event).
			</p>
			<p>
				Subqueries can also be used in all expressions including the optional <code class="literal">where</code> clause.
			</p>
			<p>
				This example demonstrates a correlated subquery in an assignment expression and also demonstrates the optional <code class="literal">as</code> keyword. It assigns the <code class="literal">phone</code> property of an <code class="literal">AlertEvent</code> event a new value based on the lookup within all unique <code class="literal">PhoneEvent</code> events (according to an <code class="literal">empid</code> property) correlating the <code class="literal">AlertEvent</code> property <code class="literal">reporter</code> with the <code class="literal">empid</code> property of <code class="literal">PhoneEvent</code>:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">update istream AlertEvent as ae
  set phone = 
    (select phone from PhoneEvent#unique(empid) where empid = ae.reporter)</pre>
			<p>
				When updating indexed properties use the syntax <span class="emphasis"><em>propertyName</em></span><code class="literal">[</code><span class="emphasis"><em>index</em></span><code class="literal">] = </code><span class="emphasis"><em>value</em></span> with the index value being an integer number.
				When updating mapped properties use the syntax <span class="emphasis"><em>propertyName</em></span><code class="literal">(</code><span class="emphasis"><em>key</em></span><code class="literal">) = </code><span class="emphasis"><em>value</em></span> with the key being a string value.
			</p>
			<p>
				When using <code class="literal">update</code>, please note these limitations:
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
				<ol>
					<li>
						<p>
							Expressions may not use aggregation functions.
						</p>
					</li>
					<li>
						<p>
							The <code class="literal">prev</code> and <code class="literal">prior</code> functions may not be used.
						</p>
					</li>
					<li>
						<p>
							For underlying event representations that are Java objects, a event object class must implement the <code class="literal">java.io.Serializable</code> interface as discussed below.
						</p>
					</li>
					<li>
						<p>
							When using an XML underlying event type, event properties in the XML document representation are not available for update.
						</p>
					</li>
					<li>
						<p>
							Nested properties are not supported for update. Variant streams may also not be updated.
						</p>
					</li>
					<li>
						<p>
							<code class="literal">update istream</code> is a pre-processing step and updates take place before other statements see the event; Therefore, when using <code class="literal">@priority</code>,
							the priority assigned to the <code class="literal">update istream</code> statement only prioritizes the statement among other <code class="literal">update istream</code> statements.
						</p>
					</li>
				</ol>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="epl-update-object"></a>5.20.1. Immutability and Updates</h3>
						</div>
					</div>
				</div>
				<p>
					When updating event objects the runtime maintains consistency across statements. The runtime ensures that an update to an event does not impact the results of statements that look for or retain the original un-updated event.
					As a result the runtime may need to copy an event object to maintain consistency.
				</p>
				<p>
					In the case your application utilizes Java objects as the underlying event representation and an <code class="literal">update</code> statement updates properties on an object, then in order to maintain consistency across statements
					it is necessary for the runtime to copy the object before changing properties (and thus not change the original object).
				</p>
				<p>
					For Java application objects, the copy operation is implemented by serialization. Your event object must therefore implement the <code class="literal">java.io.Serializable</code> interface to become eligible for update. As an alternative to serialization, you may instead configure a copy method as part of the event type configuration via <code class="literal">ConfigurationEventTypeLegacy</code>.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="epl-grouped-delivery"></a>5.21. Controlling Event Delivery : The <code class="literal">For</code> Clause</h2>
					</div>
				</div>
			</div>
			<p>
				The runtime delivers all result events of a given statement to the statement's listeners and subscriber (if any) in a single invocation of each listener and subscriber's <code class="literal">update</code> method passing an array of result events. For example, a statement using a time-batch window may provide many result events after a time period passes, a pattern may provide multiple matching events or in a join the join cardinality could be multiple rows.
			</p>
			<p>
				For statements that typically post multiple result events to listeners the <code class="literal">for</code> keyword controls the number of invocations of the runtime to listeners and subscribers and the subset of all result events delivered by each invocation.
				This can be useful when your application listener or subscriber code expects multiple invocations or expects that invocations only receive events that belong together by some additional criteria.
			</p>
			<p>
				The <code class="literal">for</code> keyword is a reserved keyword. It is followed by either the <code class="literal">grouped_delivery</code> keyword for grouped delivery or the <code class="literal">discrete_delivery</code> keyword for discrete delivery. The <code class="literal">for</code> clause is valid after any EPL select statement.
			</p>
			<p>
				The synopsis for grouped delivery is as follows:
			</p>
			<pre class="synopsis">... for grouped_delivery (<span class="emphasis"><em>group_expression</em></span> [, <span class="emphasis"><em>group_expression</em></span>] [,...])</pre>
			<p>
				The <span class="emphasis"><em>group_expression</em></span> expression list provides one or more expressions to apply to result events. The runtime invokes listeners and subscribers once for each distinct set of values returned by <span class="emphasis"><em>group_expression</em></span> expressions passing only the events for that group.
				Further detail on key expressions can be found at <a class="xref" href="epl_clauses.html#epl-syntax-compositekey" title="5.2.13. Composite Keys and Array Values as Keys">Section 5.2.13, “Composite Keys and Array Values as Keys”</a>.
			</p>
			<p>
				The synopsis for discrete delivery is as follows:
			</p>
			<pre class="synopsis">... for discrete_delivery</pre>
			<p>
				With discrete delivery the runtime invokes listeners and subscribers once for each result event passing a single result event in each invocation.
			</p>
			<p>
				Consider the following example without <code class="literal">for</code>-clause. The time batch data window collects RFIDEvent events for 10 seconds and posts an array of result events:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RFIDEvent#time_batch(10 sec)</pre>
			<p>
				Let's consider an example event sequence as follows:
			</p>
			<div class="table"><a id="d0e15998"></a>
				<p class="title"><b>Table 5.10. Sample Sequence of Events for <code class="literal">For</code> Keyword</b></p>
				<div class="table-contents">
					<table summary="Sample Sequence of Events for For Keyword" border="1">
						<colgroup>
							<col>
						</colgroup>
						<thead>
							<tr>
								<th>Event</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>RFIDEvent(id:1, zone:'A')</td>
							</tr>
							<tr>
								<td>RFIDEvent(id:2, zone:'B')</td>
							</tr>
							<tr>
								<td>RFIDEvent(id:3, zone:'A')</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div><br class="table-break">
			<p>
				Without <code class="literal">for</code>-clause and after the 10-second time period passes, the runtime delivers an array of 3 events in a single invocation to listeners and the subscriber.
			</p>
			<p>
				The next example specifies the <code class="literal">for</code>-clause and grouped delivery by zone:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RFIDEvent#time_batch(10 sec) for grouped_delivery (zone)</pre>
			<p>
				With grouped delivery and after the 10-second time period passes, the above statement delivers result events in two invocations to listeners and the subscriber: The first invocation delivers an array of two events that contains zone A events with id 1 and 3. The second invocation delivers an array of 1 event that contains a zone B event with id 2.
			</p>
			<p>
				The next example specifies the <code class="literal">for</code>-clause and discrete delivery:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from RFIDEvent#time_batch(10 sec) for discrete_delivery</pre>
			<p>
				With discrete delivery and after the 10-second time period passes, the above statement delivers result events in three invocations to listeners and the subscriber: The first invocation delivers an array of 1 event that contains the event with id 1, the second invocation delivers an array of 1 event that contains the event with id 2 and the third invocation delivers an array of 1 event that contains the event with id 3.
			</p>
			<p>
				Remove stream events are also delivered in multiple invocations, one for each group, if your statement selects remove stream events explicitly via <code class="literal">irstream</code> or <code class="literal">rstream</code> keywords.
			</p>
			<p>
				The <code class="literal">insert into</code> for inserting events into a stream is not affected by the <code class="literal">for</code>-clause.
			</p>
			<p>
				The delivery order respects the natural sort order or the explicit sort order as provided by the <code class="literal">order by</code> clause, if present.
			</p>
			<p>
				The following are known limitations:
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
				<ol>
					<li>
						<p>
							The compiler validates <span class="emphasis"><em>group_expression</em></span> expressions against the output event type, therefore all properties specified in <span class="emphasis"><em>group_expression</em></span> expressions must occur in the <code class="literal">select</code> clause.
						</p>
					</li>
				</ol>
			</div>
		</div>
	</div>
	<ul xmlns:d="http://docbook.org/ns/docbook" class="docnav">
		<li class="previous"><a accesskey="p" href="context.html"><strong>Prev</strong>Chapter 4. Context and Context Partitions</a></li>
		<li class="up"><a accesskey="u" href="#"><strong>Top of page</strong></a></li>
		<li class="home"><a accesskey="h" href="index.html"><strong>Front page</strong></a></li>
		<li class="next"><a accesskey="n" href="nwtable.html"><strong>Next</strong>Chapter 6. EPL Reference: Named Windows and Tables</a></li>
	</ul>
</body>

</html>